[学习官方例子]TComparer

代码如下:

program TComparerTest;

{$APPTYPE CONSOLE}

uses
  SysUtils, Generics.Defaults, Generics.Collections;

type
  TIntStringComparer = class(TComparer<String>)
  public
    function Compare(const Left, Right: String): Integer; override;
  end;

  { TIntStringComparer }

function TIntStringComparer.Compare(const Left, Right: String): Integer;
begin
  Result := StrToInt(Left) - StrToInt(Right);
end;

procedure SortMemos(const Comparer: IComparer<String>);
var
  List: TList<String>;
  i: Integer;
begin
  List := TList<String>.Create();
  for i := 0 to 4 do
    List.Add('第' + IntToStr(2-i) + '个数');
  List.Sort();

  for i := 0 to 4 do
    writeln(List[i]);
  List.Free;
end;

var
  Cmp: TIntStringComparer;

begin
  Cmp := TIntStringComparer.Create();
  writeln('方法一:');
  try
    SortMemos(Cmp);
  finally
    Cmp.Free;
  end;

  writeln(#10, '方法二:');
  SortMemos(TComparer<String>.Default);

  writeln(#10, '方法三:');
  SortMemos(TStringComparer.Ordinal);

  readln;

end.

效果图:

mx32A50

posted @ 2011-10-14 00:41  wouldguan  阅读(182)  评论(0编辑  收藏  举报