Ein einfaches Beispiel für einen universellen Comparer. Nehmen wir an, wir hätten 3 Properties 'A', 'B' und 'C'. Für jede Property existiert eine ID (Zahl, Enum oder so). Man könnte das auch mit
RTTI lösen, aber so ist es 'plain old pascal'.
Delphi-Quellcode:
Type
TPropertyEnum = (A,B,C);
TSortDesc = Record
sdProperty : TPropertyEnum;
sdDescending : Boolean;
End;
TSortDescArray = Array Of TSortDesc;
Function GetValue (Const V : TMyClass; property : TPropertyEnum) : Variant;
Begin
case property of
A : return V.A;
B : return V.B;
C : return V.C;
end
end;
Function Compare (Const V1, V2 : TMyClass: SortBy : TSortDescArray) : CompareResult;
Begin
Foreach sortDesc in SortBy do begin
value1 := GetValue(V1, sortDesc, sdProperty);
value2 := GetValue(V2, sortDesc, sdProperty);
Result := CompareValue(value1, value2);
if sortDesc.sdDescending then Result := -Result;
if Result<>0 then break;
end
end;
Wenn Du nun zuerst nach A aufsteigend, dann nach B absteigend sortieren willst, dann füllst Du das Array einfach mit (A,false), (B,true);
Eigentlich ganz einfach.