【问题标题】:Why a class that implements an interface is not recognized as implementing a parent interface? [duplicate]为什么实现了接口的类不被识别为实现了父接口? [复制]
【发布时间】:2015-01-15 10:43:40
【问题描述】:

我必须编写一些接口来实现一些类。其中一些将具有“基本”行为,其他将具有一些“高级”功能。
我认为最好的方法是声明一个“基本”interface 和一个“高级”子 interface
我也试图保持对象和接口之间的松散耦合。

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

这是一个示例代码:

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 或它的后代?

谢谢

【问题讨论】:

  • 如果你想支持接口,你必须实现接口,因为每个实现类可以以不同的方式实现接口。看看pastebin.com/PkQidhFc

标签: delphi inheritance interface delphi-7


【解决方案1】:

TMyClass 不支持IParent 的原因是因为你没有说它应该这样做。这就像设计的那样。如果您希望TMyClass 支持IParent,只需在声明中说明:

TMyClass = class(TInterfacedObject, IParent, IChild)

【讨论】:

  • 我明白了,但是我错过了从IParent 派生的IChild 的意义。
猜你喜欢
  • 1970-01-01
  • 2018-10-24
  • 2012-01-18
  • 2016-03-19
  • 2010-11-18
  • 2012-07-20
  • 2015-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多