Delphi 为什么实现接口的类不被识别为实现父接口?
我必须编写一些用于实现许多类的接口。其中一些具有“基本”行为,另一些具有一些“高级”功能。Delphi 为什么实现接口的类不被识别为实现父接口?,delphi,inheritance,interface,delphi-7,Delphi,Inheritance,Interface,Delphi 7,我必须编写一些用于实现许多类的接口。其中一些具有“基本”行为,另一些具有一些“高级”功能。 我认为最好的方法是声明一个“基本”的接口和一个“高级”的子接口 我还试图保持对象和接口之间的松散耦合 现在我遇到了这个问题: 当我创建一个“高级”对象(实现子接口)时,我希望它也实现父接口,但“getInterface”和“Supports”似乎都不符合我的要求 下面是一个示例代码: type IParent = interface ['{684895A1-66A5-4E9F-A509-FCF
我认为最好的方法是声明一个“基本”的
接口
和一个“高级”的子接口
我还试图保持对象和接口之间的松散耦合 现在我遇到了这个问题:
当我创建一个“高级”对象(实现子接口)时,我希望它也实现父接口,但“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.
例如,我如何测试一个对象是否实现了IParent
或它的后代
谢谢为什么
TMyClass
不支持IParent
,是因为您没有说它应该这样做。这正是我们设计的。如果希望TMyClass
支持IParent
,只需在声明中这样说:
TMyClass = class(TInterfacedObject, IParent, IChild)
如果要支持接口,必须实现接口,因为每个实现类都可以以不同的方式实现接口。看一看,我明白了,但是我忽略了从
iPart
派生的IChild
的要点。
TMyClass = class(TInterfacedObject, IParent, IChild)