2

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

我怎样才能像德尔福一样

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;
4

1 回答 1

3

您的TBase类目前没有实现IDerived,它只实现IBase。您的TDerived类同时实现IBase (通过继承自TBaseIDerived (显式)

你应该要么

  1. TBase将您的声明更改为

    TBase =class(TInterfacedObject,IBase, IDerived)

    并实现中的IDerived方法TBase

  2. 或更改b:=TBase.Create;b:=TDerived.Create
于 2012-05-02T14:06:48.263 回答