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

不想你离开。 提交于 2019-12-06 02:27:01

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