function - Delphi函数通用

标签 function delphi generics

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

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

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;

我知道该代码无法运行,但是您能告诉我是否可以执行该操作吗?

最佳答案

就介绍一个constraint通用参数T的。它必须是一个类。

来自文档:

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 及更高版本中,此错误已修复。

要规避,请按照 David 在评论中所说的操作:

if TClass(T) = TFilterEntity then

关于function - Delphi函数通用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26115406/

相关文章:

javascript - 应该是交互式的功能,但它只能运行一次

更改函数中二维数组的值

python - 将属性分配给特定的函数实例

delphi - 在 Outlook 中添加上下文菜单项?

c# - N休眠: QueryOver in generic method

generics - 为什么我的泛型函数没有为元组单态化?

function - 将参数作为函数中的变量传递时后台会发生什么

delphi - 对角画笔样式给我黑色区域

multithreading - 线程销毁永远不会执行

swift - 如何使用内部协议(protocol)的初始值设定项在公共(public)函数中构造新值?