gpt4 book ai didi

Delphi接口(interface)继承: Why can't I access ancestor interface's members?

转载 作者:行者123 更新时间:2023-12-03 14:39:42 26 4
gpt4 key购买 nike

假设您有以下内容:

//Note the original example I posted didn't reproduce the problem so
//I created an clean example
type
IParent = interface(IInterface)
['{85A340FA-D5E5-4F37-ABDD-A75A7B3B494C}']
procedure DoSomething;
end;

IChild = interface(IParent)
['{15927C56-8CDA-4122-8ECB-920948027015}']
procedure DoSomethingElse;
end;

TGrandParent = class(TInterfacedObject)
end;

TParent = class(TGrandParent)
end;

TChild = class(TParent, IChild)
private
FChildDelegate: IChild;
public
property ChildDelegate:IChild read FChildDelegate implements IChild;
end;

TChildDelegate = class(TInterfacedObject, IChild)
public
procedure DoSomething;
procedure DoSomethingElse;
end;

我认为这将允许您调用 DoSomething 但事实似乎并非如此:

procedure CallDoSomething(Parent: TParent);
begin
if Parent is TChild then
TChild(Parent).DoSomething;
end;

很明显,编译器正在强制执行接口(interface)继承,因为除非实现了 IParent 的成员,否则两个类都不会编译。尽管如此,当实例化和使用该类时,编译器仍无法解析 IParent 的成员。

我可以通过在类声明中显式包含 IParent 来解决此问题TMyClass:

TMyClass = class(TInterfacedObject, IChild, IParent)

没关系,这解决不了任何问题。

最佳答案

如果一个实现类没有声明它支持继承接口(interface),那么该类将不会与继承接口(interface)的变量兼容赋值。您发布的代码示例应该可以正常工作(使用 IChild 接口(interface)),但是如果您尝试从 TMyClass 的实例分配给 IParent 的变量,那么您就会遇到麻烦。

原因是 COM 和 ActiveX 允许实现实现后代接口(interface)(您的 IChild),但拒绝该接口(interface)的祖先(IParent)。由于 Delphi 接口(interface)旨在与 COM 兼容,因此这就是这个愚蠢的工件的来源。

我很确定我在大约 10 或 12 年前写过一篇关于此问题的文章,但我的 Borland 博客在过渡到 Embarcadero 服务器后未能幸存。

可能有一个编译器指令可以更改此行为,我不记得了。

关于Delphi接口(interface)继承: Why can't I access ancestor interface's members?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4380002/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com