代码之家  ›  专栏  ›  技术社区  ›  Alan Clark

Delphi通用TinterFaceList是否可行?

  •  7
  • Alan Clark  · 技术社区  · 15 年前

    在Delphi2010中,我定义了一个通用的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中定义。

    1 回复  |  直到 15 年前
        1
  •  13
  •   mghie    15 年前

    不使用 TInterfaceList 作为一个基类。

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

    如果您执行多线程工作,则 脸谱 是不合适的,正如在VCL中实现的枚举数的概念一样。有关更安全地遍历一个集合的api的讨论,请参见 this blog post

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