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

时间:2012-05-02 14:02:03

标签: delphi soap interface

我可以将基础接口类型转换为派生接口。

我如何制作像Delphi

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;

1 个答案:

答案 0 :(得分:3)

您的TBase课程目前尚未实施IDerived,它只实施IBase。 您的TDerived类同时实现了IBase (通过继承TBaseIDerived (明确地)

你应该

  1. 将您的TBase声明更改为

    TBase =class(TInterfacedObject,IBase, IDerived)

    并在IDerived。{/ p>

  2. 中实施TBase方法
  3. 或将b:=TBase.Create;更改为b:=TDerived.Create;