是否有任何泛型类型实现QueryInterface?

Raf*_*cci 7 delphi generics interface

考虑以下代码:

TMyList = class(TList<IMyItem>, IMyList)
Run Code Online (Sandbox Code Playgroud)

Delphi向我显示错误:

[DCC Error] test.pas(104): E2003 Undeclared identifier: 'QueryInterface'
Run Code Online (Sandbox Code Playgroud)

是否有实现的通用列表IInterface

Dav*_*nan 10

这些类Generics.Collections没有实现IInterface.您必须自己在派生类中引入它并提供标准实现.或者找到一个不同的第三方容器类集合.

例如:

TInterfacedList<T> = class(TList<T>, IInterface)
protected
  FRefCount: Integer;
  function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
  function _AddRef: Integer; stdcall;
  function _Release: Integer; stdcall;
end;

function TInterfacedList<T>.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
  if GetInterface(IID, Obj) then
    Result := 0
  else
    Result := E_NOINTERFACE;
end;

function TInterfacedList<T>._AddRef: Integer;
begin
  Result := InterlockedIncrement(FRefCount);
end;

function TInterfacedList<T>._Release: Integer;
begin
  Result := InterlockedDecrement(FRefCount);
  if Result = 0 then
    Destroy;
end;
Run Code Online (Sandbox Code Playgroud)

然后,您可以声明您的专业类:

TMyList = class(TInterfacedList<IMyItem>, IMyList)
Run Code Online (Sandbox Code Playgroud)

请记住,您需要像使用引用计数生命周期管理的任何其他类一样对待此类.只能通过接口引用它.

你真的想做更多的工作才有TInterfacedList<T>用.您需要声明一个IList<T>可以公开列表功能的内容.它会是这样的:

IList<T> = interface
  function Add(const Value: T): Integer;
  procedure Insert(Index: Integer; const Value: T);
  .... etc. etc.
end;
Run Code Online (Sandbox Code Playgroud)

然后,您可以简单地添加IList<T>到支持的接口列表,TInterfacedList<T>基类TList<T>将完成接口契约.

TInterfacedList<T> = class(TList<T>, IInterface, IList<T>)
Run Code Online (Sandbox Code Playgroud)

  • 复制TInterfaceObject的方法是否安全? (2认同)