Delphi XE中泛型数组的使用范例


本文整理自网络,侵删。

 
Delphi XE中泛型数组的使用范例,下面的范例简单的使用了泛型字符串数组,如用 TArray 代替 array of Word, 还可以使用 TArray 类提供的算法(就是少了点). 

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 aaa
end;
 
{测试 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 1
end;
//该代码片段来自于: http://www.sharejs.com/codes/delphi/9000

相关阅读 >>

Delphi with 语句的妙用

Delphi webbroker 制作网站

Delphi xe8 中tidtcpclient的writeln编码变化

Delphi vclzip实现分卷压缩

Delphi如何过xp的防火墙而不被拦截

Delphi连接mysql出现乱码

Delphi 获取memo文本光标的位置

Delphi 自动复制到指定目录的代码

Delphi idtcpclient1实现端口扫描器

Delphi cb_addstring 与lb_addstring的区别?

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...