随笔 - 2146  文章 - 97 评论 - 11767 trackbacks - 253

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses Generics.Collections, Generics.Defaults;

var
  i: Integer;
  str: string;

//无参数的建立
procedure TForm1.Button1Click(Sender: TObject);
var
  List: TList<Integer>;
begin
  List := TList<Integer>.Create();

  List.AddRange([11,22,33]);
  str := '';
  for i in List do str := str + IntToStr(i) + ' ';
  ShowMessage(str); {11 22 33 }

  List.Free;
end;

//可以基于另一个列表建立
procedure TForm1.Button2Click(Sender: TObject);
var
  List,ListTmp: TList<Integer>;
begin
  ListTmp := TList<Integer>.Create();
  ListTmp.AddRange([1, 2, 3]);

  List := TList<Integer>.Create(ListTmp);

  str := '';
  for i in List do str := str + IntToStr(i) + ' ';
  ShowMessage(str); {1 2 3 }

  ListTmp.Free;
  List.Free;
end;

//可在建立时同时指定排序器
procedure TForm1.Button3Click(Sender: TObject);
var
  List: TList<Integer>;
  Comparer: IComparer<Integer>;
begin
  {建立排序器}
  Comparer := TComparer<Integer>.Construct(
    function(const n1,n2: Integer): Integer
    begin
      Result := n2 - n1;
    end
  );

  List := TList<Integer>.Create(Comparer);
  List.AddRange([2, 3, 1]);

  List.Sort; {会根据建立时指定的排序器排序}

  str := '';
  for i in List do str := str + IntToStr(i) + ' ';
  ShowMessage(str); {3 2 1 }

  List.Free;
end;

end.

posted on 2009-10-11 12:59  万一  阅读(...)  评论(...编辑  收藏