如何使用泛型代替一堆使用不同类型的重载方法? [英] How to use generics as a replacement for a bunch of overloaded methods working with different types?
问题描述
我有一堆重载的方法,所有方法都获得一个某种类型的数组作为参数,并从该数组返回一个随机值:
I have a bunch of overloaded methods, all of them get an array of some type as a parameter and return a random value from that array:
function GetRandomValueFromArray(Arr: array of String): String; overload;
begin
Result := Arr[Low(Arr) + Random(High(Arr) + 1)];
end;
function GetRandomValueFromArray(Arr: array of Integer): Integer; overload;
begin
Result := Arr[Low(Arr) + Random(High(Arr) + 1)];
end;
等。
如何使用泛型为任何类型的数组创建单个方法?像这样的东西(不能在Delphi XE7中编译):
How can I use generics to create a single method for array of any type? Something like this (does not compile in Delphi XE7):
function GetRandomValueFromArray(Arr: TArray<T>): <T>;
在我阅读有关泛型的大多数问题时,请多加赞赏,对我来说仍然不清楚
Appreciate any opinion as I read most of questions about generics and it's still not clear for me is it possible at all or not?
推荐答案
要使用泛型函数,必须将其转换为类方法(怪异的限制,在我浅见)。请注意, class
函数不需要创建 TDummy
To use generic function, you have to convert it into method of class (weird limitation, in my humble opinion). Note that class
function does not require to create an instance of TDummy
TDummy = class
class function GetRandomValueFromArray<T>(const Arr: TArray<T>): T;
end;
class function TDummy.GetRandomValueFromArray<T>(const Arr: TArray<T>): T;
begin
Result := Arr[Low(Arr) + Random(High(Arr) + 1)];
end;
intValue := TDummy.GetRandomValueFromArray<Integer>([1,3,5]);
这篇关于如何使用泛型代替一堆使用不同类型的重载方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!