2014-09-30 100 views
2

我想創建一個通用函數。我是通用的新手。 我有3個不同類型的私人列表。我想要一個公共的泛型方法來返回列表的一個項目。德爾福功能通用

我的代碼如下。 (我把它simplifie)

TFilter = class 
private 
    FListFilter   : TObjectList<TFilterEntity>; 
    FListFilterDate  : TObjectList<TFilterDate>; 
    FListFilterRensParam : TObjectList<TFilterRensParam>; 
public 
    function yGetFilter<T>(iIndice : integer) : T; 
.... 
function TFilter .yGetFilter<T>(iIndice : integer) : T; 
begin 
    if T = TFilterEntity then 
     result := T(FListFilter.Items[iIndice]) 
    else 
     .... 
end; 

我知道,代碼不能運行,但你可以告訴我,如果這是可以做到的事情是什麼呢?

+2

這看起來像一個弱使用泛型。任何時候你必須包含一個運行時類型測試,通常意味着設計很差。我懷疑你可以做得更好。 – 2014-09-30 07:59:13

回答

3

只需引入通用參數Tconstraint即可。它必須是一個班級。

從文檔:

A type parameter may be constrained by zero or one class type. As with interface type constraints, this declaration means that the compiler will require any concrete type passed as an argument to the constrained type param to be assignment compatible with the constraint class. Compatibility of class types follows the normal rules of OOP type compatibilty - descendent types can be passed where their ancestor types are required.

更改聲明:

function yGetFilter<T:class>(iIndice : integer) : T; 

更新

看來,XE5和早期你得到一個編譯錯誤:

E2015 Operator not applicable to this operand type

在這一行:

if T = TFilterEntity then 

在XE6和此bug以上是固定的。

爲了規避,做到大衛說,在註釋:

if TClass(T) = TFilterEntity then 
+0

您確定函數的約束與類的約束類似嗎?我有這個錯誤:[dcc32 Erreur] YP.Filter.ListFilter.pas(307):E2029',',';' (e) – Joc02 2014-09-30 08:59:15

+0

+1,但你需要一個額外的演員'如果TClass(T)= TFilterEntity然後'使編譯器高興 – 2014-09-30 09:03:20

+0

現在編譯器很高興!謝謝 – Joc02 2014-09-30 09:08:47