delphi - 如何实现两个具有相同名称方法的接口(interface)?

标签 delphi inheritance interface tinterfacedobject

我试图声明一个自定义的接口(interface)列表,我想从中继承以获得特定接口(interface)的列表(我知道 IInterfaceList,这只是一个示例)。我使用的是 Delphi 2007,所以我无法访问实际的泛型(可怜我)。

这是一个简化的示例:

   ICustomInterfaceList = interface
      procedure Add(AInterface: IInterface);
      function GetFirst: IInterface;
   end;

   TCustomInterfaceList = class(TInterfacedObject, ICustomInterfaceList)
   public
      procedure Add(AInterface: IInterface);
      function GetFirst: IInterface;
   end;

   ISpecificInterface = interface(IInterface)
   end;

   ISpecificInterfaceList = interface(ICustomInterfaceList)
      function GetFirst: ISpecificInterface;
   end;

   TSpecificInterfaceList = class(TCustomInterfaceList, ISpecificInterfaceList)
   public
      function GetFirst: ISpecificInterface;
   end;

TSpecificInterfaceList 将无法编译:

E2211 Declaration of 'GetFirst' differs from declaration in interface 'ISpecificInterfaceList'

我想理论上我可以使用 TCustomInterfaceList 但我不想每次使用它时都必须强制转换“GetFirst”。我的目标是拥有一个既继承基类的行为又包装“GetFirst”的特定类。

我怎样才能实现这个目标?

谢谢!

最佳答案

ISpecificInterfaceList 定义了三个方法。他们是:

procedure Add(AInterface: IInterface);
function GetFirst: IInterface;
function GetFirst: ISpecificInterface;

因为您的两个函数共享相同的名称,所以您需要帮助编译器识别哪个函数是哪个函数。

使用 method resolution clause

TSpecificInterfaceList = class(TCustomInterfaceList, ISpecificInterfaceList)
public
  function GetFirstSpecific: ISpecificInterface;
  function ISpecificInterfaceList.GetFirst = GetFirstSpecific;
end;

关于delphi - 如何实现两个具有相同名称方法的接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27929314/

相关文章:

delphi - 有趣的 Delphi 开源应用程序/项目(不是组件/组件包!)

css - 从Intraweb区域删除所有内联样式

delphi - TThread.resume 在 Delphi-2010 中已弃用,应该在什么地方使用?

python - 在 Python2 中,如何在不明确要求最终用户包含它的情况下强制子类方法调用父方法?

postgresql - PostgreSQL中的"Abstract"表(继承)

go - golang中的隐式接口(interface)转换

delphi - 以其他形式使用声明的公共(public)变量时的编译器错误

C++ 在子类中更改父类

java - 我可以将方法参数限制为仅某些 Enum 成员吗?

angular - 如何创建一个接口(interface)来以 Angular 方式制作http响应类型?