delphi - 测试接口(interface)是否等于类型参数

标签 delphi generics interface

我有一个可以容纳接口(interface)的列表。
我想要一个删除功能,它只删除支持特定接口(interface)的项目。

type
  TMyList<T: IFoo> = class
    procedure Remove(const Item: T); overload; 
    procedure Remove<I: IBar>(const Item: T); overload;
  end;

procedure TMyList<T>.Remove<I>(const Item: T);
begin
  if Supports(Item, I) then Remove(Item);
end;

E2250 There is no overloaded version of 'Supports' that can be called with these arguments



有没有办法可以做到这一点?

最佳答案

是的,虽然您不能像这样传递接口(interface)类型参数,但您可以传递 TGUID并将接口(interface)类型分配给 TGUID ,前提是您首先在接口(interface)声明中声明了 GUID。

例子

type
  IFoo = interface
    ['{93863A49-5014-4AE5-A7CF-F3F2E044CE57}']  //<Ctrl>+<Shift>+G
   ....
  end;

  IBar = interface(IFoo)
    ['{88888888-5014-4AE5-A7CF-F3F2E044CE57}']
    ....
  end;

  procedure TFooList.Remove(const Item: IFoo; const MustBeA: TGuid); {overload;}
  begin
    if Supports(Item, MustBeA) then Remove(Item);

  ....
  for i:= 0 to count-1 do begin
    //Only remove IBar16 items
    MyFooList.Remove(FooList[i], IBar16);
  end;

关于delphi - 测试接口(interface)是否等于类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43679740/

相关文章:

delphi - 是否可以更改虚拟字符串树中行的颜色?

swift - 无法将协议(protocol)的通用关联类型的值转换为预期的参数类型

delphi - 为什么编译器对我的泛型函数参数提示 "incompatible types"?

oop - 如何处理 "optional interfaces"?

c++ - 如何使用 C++ 中的 gtest 测试具有不同构造函数的多个接口(interface)实现?

c++ - 在 Delphi 中实现 C DLL

delphi - 在delphi Canvas 上模拟高亮笔

xml - 创建和解析 XML 文档的最佳实践

c# - 在反序列化期间委托(delegate)调用泛型类内部的泛型方法挂住 CPU

c++ - 创建一种接口(interface) C++