2009-07-30 147 views
2

我有問題獲得仿製藥在以下情況下工作:接口和泛型

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' 

我嘗試了幾件事情,但無法讓它工作。

任何人在尋求幫助?謝謝!

回答

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應該可以媲美 - 但我嫌疑這是更明智的改變TComparableString

+0

我試過了。它會導致以下錯誤:「E2514類型參數'VALUE_TYPE'必須支持接口'IComparable '」 – jpfollenius 2009-07-30 09:43:13