代码如下:
program TCustomComparerTest; {$APPTYPE CONSOLE} uses SysUtils, Generics.Defaults, Generics.Collections; type TCustomerStringComparer = class(TCustomComparer<String>) public function Compare(const Left, Right: String): Integer; override; function Equals(const Left, Right: String): Boolean; override; function GethashCode(const Value: String): Integer; override; end; { TCustomerStringComparer } function TCustomerStringComparer.Compare(const Left, Right: String): Integer; begin Result := CompareText(Left, Right); end; function TCustomerStringComparer.Equals(const Left, Right: String): Boolean; begin Result := CompareText(Left, Right)=0; end; function TCustomerStringComparer.GethashCode(const Value: String): Integer; begin Result := Length(Value); end; procedure btSortClick(); var List: TList<string>; i: Integer; begin List := TList<string>.Create(TCustomerStringComparer.Create()); for i := 0 to 5 do List.Add('第'+IntToStr(8-i)+'个数'); List.Sort; for i := 0 to 5 do writeln(List[i]); List.Free; end; procedure btCountClick(); var Dictionary: TDictionary<String, Cardinal>; i: Integer; AString: string; begin Dictionary := TDictionary<String, Cardinal>.Create(TCustomerStringComparer.Create()); for i := 0 to 5 do begin AString := '第'+IntToStr(i)+'个数'; if Dictionary.ContainsKey(AString) then Dictionary[AString] := Dictionary[AString] + 1 else Dictionary.Add(AString, 1); end; for AString in Dictionary.Keys do writeln(AString+':'+UIntToStr(Dictionary[AString])); Dictionary.Free; end; begin writeln('btSortClick:'); btSortClick; writeln(#10,'btSortClick:'); btCountClick; readln; end.
效果图: