【发布时间】:2020-12-27 21:23:46
【问题描述】:
我有下面的代码。 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.
【问题讨论】:
-
解决方案是类型转换:
i := TAnimalFactory.GetAnimal(atCat) as ICat; -
感谢您的回复,我会尝试使用类型转换。结果的错误我在 Stackoverflow 中编码:-)
-
你还应该声明实现对象实现了 IAnimal
标签: delphi inheritance interface