【发布时间】:2015-11-12 00:56:34
【问题描述】:
Delphi 允许使用implements 关键字进行接口委托。
例如
IIndep1 = interface
function foo2: integer;
end;
IIndep2 = interface
function goo2: integer;
end;
TIndep1And2 = class(TInterfacedObject, IIndep1, IIndep2)
private
FNested : IIndep1; //e.g. passed via constructor or internally created (not shown here)
public
Constructor Create(AIndep1: IIndep1);
function goo2: integer;
property AsIndep1 : IIndep1 read FNested implements IIndep1;
end;
这很好用,但不适用于继承的接口。 (错误信息“缺少接口方法ILev1.foo的实现”)
ILev1 = interface
function foo: Integer;
end;
ILev2 = interface(ILev1)
function goo: Integer;
end;
TLev2Fails = class(TInterfacedObject, ILev1, ILev2) //Also fails with ILev2 alone (Error: "ILev1 not mentioned in interface list")
private
FNested : ILev1; //passed via constructor or internally created
public
Constructor Create(AILev1: ILev1);
function goo: Integer;
property AsLev1 : ILev1 read FNested implements ILev1;
end;
解决方法是添加一个额外的祖先类
TLev1Wrapper = class(TInterfacedObject, ILev1)
private
FNested : ILev1; //passed via constructor or internally created
public
Constructor Create(AILev1: ILev1);
property AsLev1 : ILev1 read FNested implements ILev1;
end;
TLev2Works = class(TLev1Wrapper, ILev2)
public
function goo: Integer;
end;
有没有办法避免包装类的祖先?
[编辑]
只是关于接口委托的说明,使用implements 的目的是避免直接满足接口,而是将该要求传递给聚合或组合成员。提供完整的界面并手动委派给组合成员会破坏使用implements 引导界面所获得的好处。事实上,在这种情况下,implements 关键字和属性可能会被删除。
【问题讨论】:
-
我认为这一定是编译器错误。我查看了文档,没有看到任何与此限制相关的内容。
-
感谢@RudyVeldthuis 指出问题在于无法绑定的 ILev2.foo。
-
@Graymatter 感谢以下 cmets 中的链接。我来回讨论这是否是一个错误。很可能是一个
标签: delphi interface delphi-xe2 delphi-xe4 delphi-xe8