我想创建一个通用函数。我是通用的新手。 我有 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/