gpt4 book ai didi

delphi - for ... in 带接口(interface)

转载 作者:行者123 更新时间:2023-12-03 19:03:02 25 4
gpt4 key购买 nike

我正在尝试浏览对象列表,但我只想提供由我的对象实现的接口(interface)。

我有两种情况:只是在内部枚举我的列表(这不是什么大问题,我可以只使用对象而不是接口(interface))和一个属性。

ITemplate = interface
...
end;

TTemplate = class (TInterfacedObject, ITemplate)
...
end;

TMyClass = class
strict private
FTemplates: TObjectList<TTemplate>;
function GetTemplates: IEnumerable<ITemplate>;
...
public
property Templates: IEnumerable<ITemplate> read GetTemplates;

...

procedure TMyClass.LoopTroughInternally;
var
template: ITemplate;
begin
for template in FTemplates do // isn't working, of course
foobar(template);
end;

function TMyClass.GetTemplates: IEnumerable<ITemplate>;
begin
// dunno what to do here...
end;

有没有办法在不实现特定 IEnumerable 的情况下提供此枚举器?

最佳答案

从表面上看,您只需更改局部变量 templateTTemplate 类型然后你就完成了。如果此代码是内部代码,则无需执行任何其他操作。

但是,在我看来,您的问题更大。

type
TTemplate = class(TInterfacedObject, ITemplate)
...
end;

....

FTemplates: TObjectList<TTemplate>;

这是一个大错误。当您从 TInterfacedObject 继承时您是说生命周期由接口(interface)引用计数管理。这意味着您必须停止使用非引用计数引用。因为它们很容易变得陈旧。当您使用 TTemplate 时,您正在使用非引用计数引用引用。您可以使用 TObjectList<T> 来复合问题这都是关于生命周期管理的。

避免这种情况的简单方法是使用接口(interface)列表而不是 TObjectList<T> .
FTemplates: TList<ITemplate>;

现在,您已经完成并尘埃落定,因为您确实可以写
for template in FTemplates do

在哪里 templateITemplate .

关于delphi - for ... in 带接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27174943/

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