【发布时间】:2021-12-08 17:23:41
【问题描述】:
tl;博士:
试图将对象列表传递给函数,该函数需要实现接口的对象列表。所述对象实现该接口。编译器不允许这样做。
寻找替代解决方法或我的错误。
设置
我没有使用实际代码,这在 IMO 中应该没有关系。对我来说似乎是一个概念问题。
TObjectWithInterface 类实现了ISomeInterface 接口并扩展了TCustomInterfacedObject 类,该类仅围绕IInterface 的引用计数工作,如documentation 中给出的那样。
TObjectWithInterface = class(TCustomInterfacedObject, ISomeInterface)
如果有一个过程接受实现该接口的对象列表:
procedure SomeFunction(List: TList<ISomeInterface>)
问题
在TObjectWithInterface 的函数内部,我尝试使用TObjectWithInterface 的对象列表调用该函数:
procedure TObjectWithInterface.DoTheStuff(ListOfObjects: TList<TObjectWithInterface>)
begin
// ...
SomeFunction(ListOfObjects); // <-- Compiler error: Incompatible types
// ...
end;
编译器告诉我以下内容:
E2010:不兼容的类型:“System.Generics.Collections.TList”和“System.Generics.Collections.TList”
愚蠢的解决方法
我真的不喜欢我目前的解决方法,它包括创建一个新列表并将每个TObjectWithInterface 类型转换为ISomeInterface:
procedure TObjectWithInterface.DoTheStuff(ListOfObjects: TList<TObjectWithInterface>)
var
ListOfInterfaceObjects: TList<ISomeInterface>;
begin
// ...
ListOfInterfaceObjects := TList<ISomeInterface>.Create;
for var Object in ListOfObjects do
ListOfInterfaceObjects.Add(Objects as ISomeInterface);
SomeFunction(ListOfInterfaceObjects)
// ...
end;
这对我来说似乎很 hacky。我可能做了一些愚蠢的事情,或者没有正确理解某些事情,因为这是我第一次尝试在 Delphi 中使用接口。请不要生气。
无论哪种方式,我希望有人能指出我的错误,或者,如果这是语言限制,有其他解决方法。
【问题讨论】: