How to use generics as a replacement for a bunch of overloaded methods working with different types?

久未见 提交于 2020-02-02 07:36:44

问题


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;

etc.

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?


回答1:


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]);


来源:https://stackoverflow.com/questions/48423105/how-to-use-generics-as-a-replacement-for-a-bunch-of-overloaded-methods-working-w

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