gpt4 book ai didi

delphi - 多接口(interface)继承Delphi

转载 作者:行者123 更新时间:2023-12-01 23:48:27 24 4
gpt4 key购买 nike

我有下面的代码。 IAnimal 是我的应用程序中所有动物的基本接口(interface)。

为什么我不能用我想要的类型声明 var,获取一个实现基本接口(interface) 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.

最佳答案

在现代的 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;

关于delphi - 多接口(interface)继承Delphi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63811729/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com