Delphi 接口和泛型

Delphi 接口和泛型,delphi,generics,interface,delphi-2009,Delphi,Generics,Interface,Delphi 2009,在以下场景中,我很难让泛型工作: Delphi提供了接口IComparable: IComparable <T> = interface function CompareTo (Value : T) : Integer; end; 实现两个接口的类的一个示例: TComparableString = class (TInterfacedObject, IComparable <String>, IPersistent) strict private FValue

在以下场景中,我很难让泛型工作:

Delphi提供了接口IComparable:

IComparable <T> = interface
  function CompareTo (Value : T) : Integer;
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;
我试过几种方法,但都没用


有人来帮忙吗?谢谢

您的
TComparableString
类没有实现非泛型的
IComparable
接口,因此它不满足类型约束。您必须更改约束或实现
IComparable

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

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

TSimpleSortIndex <VALUE_TYPE : IPersistent, IComparable<VALUE_TYPE>> = 
    class (TInterfacedObject, ISortIndex <VALUE_TYPE>)
ISortIndex=接口
TSimpleSortIndex=
类别(TInterfacedObject、ISortIndex)
编辑:我没有注意到您的
TComparableString
实现了
IComparable
而不是
IComparable
。这是故意的吗?通常情况下,某些事物可以与自身的其他实例相比较,而不是与不同的类型相比较


您可以在
ISortIndex
/
tsimplesortinex
中引入另一个类型参数,以指示
VALUE\u type
应与之相比较的类型-但我认为更改
TComparableString

更明智,因为我尝试过这样做。它会导致以下错误:“E2514类型参数‘VALUE_Type’必须支持接口‘IComparable’”。我真的想在那里使用TComparableString而不是String。现在一切似乎都很好。感谢您快速准确的帮助!
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'
ISortIndex <VALUE_TYPE : IPersistent, IComparable<VALUE_TYPE>> = interface

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