接口和泛型

时间:2009-07-30 09:37:35

标签: delphi generics interface delphi-2009

我在以下场景中使用泛型有问题:

Delphi提供IComparable接口:

IComparable <T> = interface
  function CompareTo (Value : T) : Integer;
end;

我添加了另一个界面IPersistent:

IPersistent = interface
  function  ToString : String;
  procedure FromString (const Str : String);
end;

实现两个接口的类的一个示例:

TComparableString = class (TInterfacedObject, IComparable <String>, IPersistent)
strict private
  FValue : String;
public
  function  CompareTo (Value : String) : Integer;
  function  ToString : String;
  procedure FromString (const Str : String);
end;

现在有另一个具有两个接口约束的泛型类:

ISortIndex <VALUE_TYPE : IPersistent, IComparable> = interface
  ...
end;

最后是该界面的一个实现:

TSimpleSortIndex <VALUE_TYPE : IPersistent, IComparable> = class (TInterfacedObject, ISortIndex <VALUE_TYPE>)

  ...
end;

现在,当我尝试声明类似的排序索引时:

FSortIndex : ISortIndex <TComparableString>;

我收到错误消息

[DCC Error] Database.pas(172): E2514 Type parameter 'VALUE_TYPE' must support  interface 'IComparable'

我尝试了几件事,但无法让它发挥作用。

有人在寻求帮助吗?谢谢!

1 个答案:

答案 0 :(得分:6)

您的TComparableString类未实现非通用IComparable接口,因此它不满足类型约束。您必须更改约束或实施IComparable

更改约束可能是最简单的方法。我真的不懂德尔福,但看看是否有效:

ISortIndex <VALUE_TYPE : IPersistent, IComparable<VALUE_TYPE>> = interface

TSimpleSortIndex <VALUE_TYPE : IPersistent, IComparable<VALUE_TYPE>> = 
    class (TInterfacedObject, ISortIndex <VALUE_TYPE>)
编辑:我没有注意到您的TComparableString已实施IComparable<String>而不是IComparable<TComparableString>。这是故意的吗?通常某些东西可以与其他实例相媲美,而不是与其他类型的实例相比。

您可以将另一个类型参数引入ISortIndex / TSimpleSortIndex,以指明VALUE_TYPE应该与之匹配的类型 - 但我怀疑< / em>更改TComparableString更为明智。