Delphi通用的TInterfaceList可能吗?
发布时间:2020-12-15 04:16:08 所属栏目:大数据 来源:网络整理
导读:在Delphi 2010中,我定义了一个通用的TInterfaceList,如下所示: typeTInterfaceListI: IInterface = class(TInterfaceList) function GetI(index: Integer): I; procedure PutI(index: Integer; const Item: I); property Items[index: Integer]: I read Get
在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; 我还没有遇到任何问题,但这样做有什么本质上的风险吗?是否可以向其中添加一个枚举器以允许..in循环来处理它?如果它没有任何问题,我想知道为什么在RTL中还没有定义类似的东西. 解决方法
不要将TInterfaceList用作基类.
如果你做单线程工作,你可以使用TList< I:IInterface>代替.性能会更好,因为没有内部锁定. 如果你做多线程工作,TInterfaceList的公共接口是不合适的,因为它们是在VCL中实现的枚举器的概念.有关更好的API的讨论,可以安全地迭代一系列事物,请参阅this blog post. 如果您共享线程之间的接口列表,则应尽可能地将其锁定.这样做的一个好方法是实现一个线程安全的方法,该方法将一个接口数组返回给调用线程,然后可以安全地迭代它,而不保持原始列表被锁定. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |