Delphi function generic

烈酒焚心 提交于 2020-01-04 14:15:07

问题


I would like to create a generic function. I'm novice in generic. I've 3 private lists of different type. I want a public generic method for return 1 item of the list.

I've the code below. (I have it 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;

I know that code doesn't run, but can you tell me if it's possible to do a thing that it ?


回答1:


Just introduce a constraint of the generic parameter T. It has to be a class.

From the documentation:

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.

Change declaration to:

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

Update

It appears that in XE5 and earlier you get a compiler error:

E2015 Operator not applicable to this operand type

at this line:

if T = TFilterEntity then

In XE6 and above this bug is fixed.

To circumvent, do as David says in a comment:

if TClass(T) = TFilterEntity then


来源:https://stackoverflow.com/questions/26115406/delphi-function-generic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!