RAD Studio VCL Reference
|
Default returns an instance of TComparer for a given type.
class function Default: IComparer<T>;
__fastcall IComparer<T> Default();
Use the Default method to obtain an instance of TComparer for a given type. RTTI is used to determine the type information and to select the most appropriate implementation of TComparer. For example, calling TComparer<String>.Default returns an instance of TComparer that can compare string types.
Delphi Examples:
{ This example demonstrates the usage of TComparer. The example assumes two memos and three buttons are present on the form. } type { Declare a new custom comparer } TIntStringComparer = class(TComparer<String>) public function Compare(const Left, Right: String): Integer; override; end; { TIntStringComparer } function TIntStringComparer.Compare(const Left, Right: String): Integer; begin { Transform the strings into ints and perform the comparison } Result := StrToInt(Left) - StrToInt(Right); end; procedure TForm3.SortMemos(const Comparer: IComparer<String>); var List: TList<String>; I: Integer; begin { Create a new list of strings with our custom comparer } List := TList<String>.Create(Comparer); { Populate the list with numbers in the memo } for I := 0 to InMemo.Lines.Count - 1 do List.Add(InMemo.Lines[I]); { Sort the list } List.Sort(); { Copy the list with numbers to the memo } OutMemo.Clear; for I := 0 to List.Count - 1 do OutMemo.Lines.Add(List[I]); { Free resources } List.Free(); end; procedure TForm3.btCustomSortClick(Sender: TObject); begin { Use our custom comparer } SortMemos(TIntStringComparer.Create()); end; procedure TForm3.btDefaultSortClick(Sender: TObject); begin { Use the default provided comparer } SortMemos(TComparer<String>.Default); end; procedure TForm3.btOrdinalSortClick(Sender: TObject); begin { Use the ordinal string comparer } SortMemos(TStringComparer.Ordinal); end;
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
|
What do you think about this topic? Send feedback!
|