如何实现两个具有相同名称的方法的接口?

时间:2015-01-13 18:48:54

标签: delphi inheritance interface tinterfacedobject

我正在尝试声明一个自定义的接口列表,我想继承它以获取特定接口的列表(我知道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' GetFirst'与界面&ISQUificInterfaceList'

中的声明不同

我想我理论上可以使用TCustomInterfaceList,但我不想要投射" GetFirst"每次我使用它。我的目标是拥有一个特定的类,它既继承了基类的行为又包装了#34; GetFirst"。

我怎样才能做到这一点?

谢谢!

3 个答案:

答案 0 :(得分:6)

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;

答案 1 :(得分:1)

不确定Delphi7中是否也可以这样做,但您可以尝试在声明中使用方法解决条款。

function interface.interfaceMethod = implementingMethod;

如果可能,这将帮助您解决命名冲突。

答案 2 :(得分:0)

对于方法,如果参数不同,您也可以选择覆盖。

如果你后来的后代实现了一个后代接口,那么接口函数映射是很安静的,因为这些函数不会作为接口方法转发到下一个类,所以你需要重新映射它们。

相关问题