delphi – 如何在通用TList中获得最大值?
发布时间:2020-12-15 09:44:23 所属栏目:大数据 来源:网络整理
导读:在TList中获取最大值的最简单方法是什么 Integer? function GetMaximum(AList: TListInteger): Integer;begin Assert(AList.Count 0); Result := ?;end; 我读到C#有一个AList.Max,在Delphi中有类似的东西吗? 解决方法 这是一个有趣的示例,在通用容器上有Ma
在TList中获取最大值的最简单方法是什么< Integer>?
function GetMaximum(AList: TList<Integer>): Integer; begin Assert(AList.Count > 0); Result := ?; end; 我读到C#有一个AList.Max,在Delphi中有类似的东西吗? 解决方法
这是一个有趣的示例,在通用容器上有MaxValue实现:
{$APPTYPE CONSOLE} uses System.SysUtils,System.Generics.Defaults,System.Generics.Collections; type TMyList<T> = class(TList<T>) public function MaxValue: T; end; { TMyList<T> } function TMyList<T>.MaxValue: T; var i: Integer; Comparer: IComparer<T>; begin if Count=0 then raise Exception.Create('Cannot call TMyList<T>.MaxValue on an empty list'); Comparer := TComparer<T>.Default; Result := Self[0]; for i := 1 to Count-1 do if Comparer.Compare(Self[i],Result)>0 then Result := Self[i]; end; var IntList: TMyList<Integer>; DoubleList: TMyList<Double>; StringList: TMyList<string>; begin IntList := TMyList<Integer>.Create; IntList.AddRange([10,5,12,-49]); Writeln(IntList.MaxValue); DoubleList := TMyList<Double>.Create; DoubleList.AddRange([10.0,5.0,12.0,-49.0]); Writeln(DoubleList.MaxValue); StringList := TMyList<string>.Create; StringList.AddRange(['David Heffernan','Uwe Raabe','Warren P','Jens Mühlenhoff']); Writeln(StringList.MaxValue); Readln; end. 因为我们无法提出与低(整数)的通用等价物,所以当在空列表上调用该方法时,我会引发异常. 输出是: 12 1.20000000000000E+0001 Warren P (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |