Delphi通用的TInterfaceList是否可行?

Ala*_*ark 7 delphi delphi-2010

在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;
Run Code Online (Sandbox Code Playgroud)

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

mgh*_*hie 13

不要TInterfaceList用作基类.

如果你做单线程工作,你可以只使用一个TList<I: IInterface>.性能会更好,因为没有内部锁定.

如果你做多线程工作,那么公共接口TInterfaceList是不合适的,因为它们是在VCL中实现的枚举器的概念.有关更好的API的讨论,可以安全地迭代一系列内容,请参阅此博客文章.

如果您共享线程之间的接口列表,则应尽可能地将其锁定.这样做的一个好方法是实现一个线程安全的方法,该方法将一个接口数组返回给调用线程,然后可以安全地迭代它,而不保持原始列表被锁定.