接口

时间:2016-11-10 14:20:47

标签: delphi inheritance interface multiple-inheritance

有没有办法定义从两个或多个接口继承的接口?

我在Delphi2007上尝试了以下代码:

  IInterfaceA = interface
     procedure A;
  end;

  IInterfaceB = interface
    procedure B;
  end;

  IInterfaceAB = interface(IInterfaceA, IInterfaceB);

..它在第E2029 ')' expected but ',' found行引发了错误IInterfaceAB = interface(IInterfaceA, IInterfaceB)

3 个答案:

答案 0 :(得分:7)

Delphi中没有多接口继承,因为Delphi中根本没有多重继承。你所能做的就是让一个类实现多个接口。

TMyClass = class(TInterfacedObject, IInterfaceA, IInterfaceB)

答案 1 :(得分:6)

在Delphi中,接口不能继承多个接口,但是类可以实现多个接口。如果正确设计组件(查看ISP - 接口隔离原则),则不需要从接口继承接口。

答案 2 :(得分:1)

恕我直言,在这种情况下,您必须定义三种类型。 每个接口一个,多个继承的第三个:

  IInterfaceA = interface
     procedure A;
  end;

  IInterfaceB = interface
    procedure B;
  end;

  TiA = class(TInterfacedObject, IInterfaceA)
    procedure A;
  end;

  TiB = class(TInterfacedObject, IInterfaceB)
    procedure B;
  end;

  TMyObject = class(TInterfacedObject, IInterfaceA, IInterfaceB)
  private
    _iA : IInterfaceA;
    _iB : IInterfaceB;
    function getiA : IInterfaceA;
    function getiB : IInterfaceB;
  public
    property iA : IInterfaceA read getiA implements IInterfaceA;
    property iB : IInterfaceB read getiB implements IInterfaceB;
  end;
{.....}
{ TMyObject }

function TMyObject.getiA: IInterfaceA;
begin
  if not Assigned(_iA) then _iA := TIA.Create;
  Result := _iA;
end;

function TMyObject.getiB: IInterfaceB;
begin
  if not Assigned(_iB) then _iB := TIB.Create;
  Result := _iB;
end;