2010-02-09 58 views
5

德尔福2010年,我已经定义了一个通用的TInterfaceList如下:是否可以使用Delphi泛型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循环在它上面工作?如果没有问题,我想知道为什么RTL中没有定义类似的东西。

回答

11

请勿使用TInterfaceList作为基类。

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

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

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

相关问题