# 善用泛型数组

`uses Generics.Collections, Generics.Defaults;{测试 TArray 的 Sort 方法}procedure TForm1.Button1Click(Sender: TObject);var arr: TArray<string>; //同 array of string s: string;begin SetLength(arr, 5); arr[0] := 'aaa'; arr[1] := 'AAA'; arr[2] := '111'; arr[3] := '333'; arr[4] := '222'; TArray.Sort<string>(arr); Memo1.Clear; for s in arr do Memo1.Lines.Add(s); //111 222 333 AAA aaaend;{测试 TArray 的 BinarySearch 方法}procedure TForm1.Button2Click(Sender: TObject);var arr: TArray<Integer>; //同 array of Integer i,n: Integer;begin SetLength(arr, 5); for i := 0 to Length(arr) - 1 do arr[i] := Integer(Sqr(i)); Memo1.Clear; for i := Low(arr) to High(arr) do Memo1.Lines.Add(IntToStr(arr[i])); if TArray.BinarySearch<Integer>(arr, 4, n) then ShowMessage(IntToStr(n)); //2, 也就是第三个 if TArray.BinarySearch<Integer>(arr, 5, n) then ShowMessage(IntToStr(n)); //找不到时, 不能根据 n 的值判断end;{自定义排序器}procedure TForm1.Button3Click(Sender: TObject);var arr: TArray<Integer>; num: Integer;begin SetLength(arr, 5); arr[0] := 2; arr[1] := 4; arr[2] := 3; arr[3] := 1; arr[4] := 5; TArray.Sort<Integer>(arr, TComparer<Integer>.Construct( function (const a,b: Integer): Integer begin Result := b - a; end )); Memo1.Clear; for num in arr do Memo1.Lines.Add(IntToStr(num)); //5 4 3 2 1end;`