Delphi函数通用 [英] Delphi function generic

查看:116
本文介绍了Delphi函数通用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个通用函数。我是通用的新手。
我有3个不同类型的私人列表。我想要一个公共的泛型方法来返回列表中的1个项目。



我有下面的代码。 (我简化了它)

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

我知道代码无法运行,但是您能否告诉我是否可以执行某项操作那它?

只要介绍约束通用参数 T 。它必须是一个类。



从文档:


一种类型参数可能受零或一个类类型的限制。与接口类型约束一样,此声明意味着编译器将要求将作为约束类型参数参数传递的任何具体类型与约束类分配兼容。
类类型的兼容性遵循OOP类型兼容性的正常规则 - 派生类型可以在需要它们的祖先类型的地方传递。

将声明更改为:

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






更新



看来在XE5和更早的版本中会出现一个编译器错误:


E2015运算符不适用于此操作数类型

在这一行:

 如果T = TFilterEntity,那么

在XE6及更高版本中,此错误已修复。 b

为了规避,就像David在评论中所说的那样:

 如果TClass(T)= TFilterEntity那么


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 ?

解决方案

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

这篇关于Delphi函数通用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆