且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我的班级实现子接口,而不实现其父接口?

更新时间:2022-12-04 19:06:26

这似乎有点反常,但是您的类也必须声明它也实现了父接口。您的类声明必须是这样的:

This might seem a little counter intuitive, but your class must declare that it implements the parent interface, too. Your class declaration must be like so:

TMyObj = class(TInterfacedObject, IMyBase, IMyIntf)

前Borland工程师Danny Thorpe在有关问题的答案

Danny Thorpe, a former Borland engineer, explained the rationale behind this behaviour in an answer to a related question:


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

If an implementing class does not declare that it supports an inherited interface, then the class will not be assignment compatible with variables of the inherited interface. The code sample you posted should work fine (using the IChild interface), but if you try to assign from an instance of TMyClass to a variable of IParent, then you'll run into trouble.

原因是因为COM和ActiveX允许
的实现实现后代接口(您的IChild),但拒绝其中的祖先
接口(IParent)。由于Delphi接口旨在使
与COM兼容,因此这就是愚蠢的产物的来源。

The reason is because COM and ActiveX allow an implementation to implement a descendent interface (your IChild) but deny the ancestor of that interface (IParent). Since Delphi interfaces are intended to be COM compatible, that's where this goofy artifact comes from.