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

标签 delphi interface enumeration delphi-xe6

我正在尝试浏览对象列表,但我只想提供由我的对象实现的接口(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/

相关文章:

sql - Firebird sql更新命令在delphi中不起作用

delphi - 如何使用WinSpool API设置纸张尺寸?

java - 是否需要接口(interface)方法的实现

java - 创建对象枚举

delphi - Unicode 字符串上的 Length() 与 Sizeof()

java - 在具体类中调用超接口(interface)的非抽象方法

java - 为什么我无法在此 VectorQueue 实例上实现我的 Vector 方法?

java - 如何在不写入 "if statements"的情况下初始化输入字段?

php - Zend Mysql 获取 ENUM 值

css - 如何获取 IHTMLElement 的所有 IHTMLStyle 属性?