为什么实现接口的类不被识别为实现父接口?

时间:2014-11-18 09:41:05

标签: delphi inheritance interface delphi-7

我必须编写一些用于实现许多类的接口。其中一些将具有“基本”行为,而另一些则具有一些“高级”特征 我认为最好的方法是宣布“基本”interface和“高级”孩子interface
我也试图在对象和接口之间保持松耦合。

现在我遇到了这个问题:
当我创建一个“高级”对象(实现Child接口)时,我希望它也实现了Parent接口,但“getInterface”和“Supports”似乎都不同意我。

以下是示例代码:

type
  IParent = interface
    ['{684895A1-66A5-4E9F-A509-FCF739F3F227}']
    function ParentFunction: String;
  end;

  IChild = interface(IParent)
    ['{B785591A-E816-4D90-BA01-1FFF865D312A}']
    function ChildFunction: String;
  end;

  TMyClass = class(TInterfacedObject, IChild)
  public
    function ParentFunction: String;
    function ChildFunction: String;
  end;

function TMyClass.ChildFunction: String;
begin
  Result := 'ChildFunction';
end;

function TMyClass.ParentFunction: String;
begin
  Result := 'ParentFunction';
end;

var
  Obj: TMyClass;
  ParentObj: IParent;
  ChildObj: IChild;
begin

  Obj := TMyClass.Create;
  ChildObj := Obj;
  WriteLn(Format('%s as IChild: %s', [Obj.ClassName, ChildObj.ChildFunction]));
  WriteLn(Format('%s as IChild: %s', [Obj.ClassName, ChildObj.ParentFunction]));

  if (Obj.GetInterface(IParent, ParentObj)) then
    WriteLn(Format('GetInterface: %s as IParent: %s', [Obj.ClassName, ParentObj.ParentFunction]))
  else
    WriteLn(Format('GetInterface: %s DOES NOT implement IParent', [Obj.ClassName])); // <-- Why?

  ParentObj := ChildObj;
  WriteLn(Format('%s as IParent: %s', [Obj.ClassName, ParentObj.ParentFunction]));

  if (Supports(Obj, IParent)) then
    WriteLn(Format('Supports: %s Supports IParent', [Obj.ClassName]))
  else
    WriteLn(Format('Supports: %s DOES NOT Support IParent', [Obj.ClassName]));   // <-- Why?

end.

以下是结果:

TMyClass as IChild: ChildFunction
TMyClass as IChild: ParentFunction
GetInterface: TMyClass DOES NOT implement IParent
TMyClass as IParent: ParentFunction
Supports: TMyClass DOES NOT Support IParent

例如,我如何测试对象是否实现了IParent或它的后代?

谢谢

1 个答案:

答案 0 :(得分:2)

TMyClass不支持IParent的原因是因为您没有说它应该这样做。这与设计一样。如果您希望TMyClass支持IParent,请在声明中说明:

TMyClass = class(TInterfacedObject, IParent, IChild)