gpt4 book ai didi

delphi - 我可以将 Base 类型转换为 Derived 接口(interface)类型吗?

转载 作者:行者123 更新时间:2023-12-03 18:32:59 24 4
gpt4 key购买 nike

我可以将基本接口(interface)类型转换为派生接口(interface)吗?

我怎样才能像德尔福一样

Delphi 生成代码/Delphi 7:

function TXMLBook.Get_Id: IXMLId;
begin
Result := ChildNodes['id'] as IXMLId;
end;

ChildNodes['id'] 是基本类型 IXMLNode

IXMLId 是从 IXMLNode 派生的类型

我的示例代码是:

type
IBase = interface(IInterface)
['{5CEA3668-36CB-444C-8D3E-06644070A2B4}']
function Test:AnsiString;
end;

TBase =class(TInterfacedObject,IBase)
function Test:AnsiString;
end;

IDerived =interface (IBase)
['{8CDB2982-43B0-4636-B6F5-2561C0D419A9}']
function Test2: AnsiString;
end;

TDerived=class (TBase,IDerived)
function Test:AnsiString;
function Test2:AnsiString;
end;

{ TBase }

function TBase.Test: AnsiString;
begin
Result:='Base Test';
end;

{ TDerived }

function TDerived.Test: AnsiString;
begin
Result:='Derived Test';
end;

function TDerived.Test2: AnsiString;
begin
Result:='Derived Test2';
end;

procedure TForm1.Button1Click(Sender: TObject);
var
b:IBase;
d: IDerived;
begin
b:=TBase.Create;
d:=b as IDerived; // Error : Interface not supported

ShowMessage(b.Test);
end;

最佳答案

您的 TBase类当前未实现 IDerived , 它只实现 IBase .
您的 TDerived类同时实现 IBase (通过继承 TBase )和 IDerived (明确)。

你应该要么

  • 更改您的 TBase声明
    TBase =class(TInterfacedObject,IBase, IDerived)
    并实现 IDerived TBase 中的方法.
  • 或更改 b:=TBase.Create;b:=TDerived.Create ;
  • 关于delphi - 我可以将 Base 类型转换为 Derived 接口(interface)类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10415344/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com