【问题标题】:Is Delphi generic TInterfaceList possible?Delphi 通用 TInterfaceList 可能吗?
【发布时间】:2010-02-09 11:45:28
【问题描述】:

在 Delphi 2010 中,我定义了一个通用的 TInterfaceList 如下:

type

TInterfaceList<I: IInterface> = class(TInterfaceList)
  function GetI(index: Integer): I;
  procedure PutI(index: Integer; const Item: I);
  property Items[index: Integer]: I read GetI write PutI; default;
end;

implementation

function TInterfaceList<I>.GetI(index: Integer): I;
begin
  result := I(inherited Get(Index));
end;

procedure TInterfaceList<I>.PutI(index: Integer; const Item: I);
begin
  inherited Add(Item);
end;

我还没有遇到任何问题,但是这样做有什么固有的风险吗?是否可以向它添加一个枚举器以允许 for..in 循环对其进行处理?如果没有问题,我想知道为什么 RTL 中还没有定义类似的东西。

【问题讨论】:

    标签: delphi delphi-2010


    【解决方案1】:

    不要使用TInterfaceList 作为基类。

    如果您执行单线程工作,您可以只使用TList&lt;I: IInterface&gt;。性能会更好,因为没有内部锁定。

    如果你做多线程工作,TInterfaceList 的公共接口是不合适的,因为枚举器的概念是在 VCL 中实现的。有关更好的 API 以安全地迭代一系列事物的讨论,请参阅 this blog post

    如果你在线程之间共享你的接口列表,你应该尽可能短地锁定它。一个很好的方法是实现一个线程安全的方法,该方法将接口数组返回给调用线程,然后可以安全地对其进行迭代,而无需锁定原始列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-04
      • 2011-06-12
      • 1970-01-01
      • 2011-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多