多接口继承Delphi

Bos*_*oss 2 delphi inheritance interface

我有下面的代码。IAnimal 是我的应用程序中所有动物的基本界面。

为什么我不能用我想要的类型声明 var,获取一个实现基接口 IAnimal 的对象并调用该方法?

type
  IAnimal = interface
  end;

  ICat = interface(IAnimal)
    procedure Hunt;
  end;

  IBird = interface(IAnimal)
    procedure Fly;
  end;

  TCat = class(TInterfacedObject, ICat)
    procedure Hunt;
  end;

  TBird = class(TInterfacedObject, IBird)
    procedure Fly;
  end;

  TAnimalType = (atCat, atBird);

  TAnimalFactory = class
    class function GetAnimal(aType: TAnimalType): IAnimal;
  end;

procedure TCat.Hunt;
begin
  Writeln('I hunt');
end;

procedure TBird.Fly;
begin
  Writeln('I fly');
end;
        
class function TAnimalFactory.GetAnimal(aType: TAnimalType): IAnimal;
begin
  case aType of
    atCat: Result := TCat.Create;
    atBird: Result := TBird.Create;
  end;
end;

var
  i: ICat;
begin
    i := TAnimalFactory.GetAnimal(atCat);
    // [dcc32 Error] Project1.dpr(63): E2010 Incompatible types: 'ICat' and 'IAnimal'

    i.Hunt;
end.
Run Code Online (Sandbox Code Playgroud)

kam*_*ami 5

在现代 Delphi 版本中,您可以使用泛型,如下所示:

interface
uses
  System.Classes,
  System.Generics.Collections;

  ICat = interface(IAnimal)
    ['{15E79A9B-CF33-4672-8892-FCBC7A778C57}']  // Ctrl+Shift+G to generate GUID
    procedure Hunt;
  end;

  IBird = interface(IAnimal)
    ['{C9318161-2827-4D8C-AE0F-4D7B9A686F60}']
    procedure Fly;
  end;

  TAnimalFactory = class
    class function GetAnimal<Intf: IAnimal>: Intf;
  end;

implementation
uses
  System.SysUtils,
  System.TypInfo;
  { TAnimalFactory }

class function TAnimalFactory.GetAnimal<Intf>: Intf;
var
  G: TGUID;
  tmp: IInterface;
begin
  G := GetTypeData(TypeInfo(Intf))^.Guid;

  if G = ICat then
    tmp:=TCat.Create;
  if G = IBird then
    tmp:=TBird.Create;

  if not Supports(tmp, G, Result) then
    Result:=nil;
end;

var
  i: ICat;
begin
  i := TAnimalFactory.GetAnimal<ICat>;
  if Assigned(i) then  // if you not sure about interface support
    i.Hunt;
end;
Run Code Online (Sandbox Code Playgroud)