unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
//Pro Klasse eigentlich eine eigene Unit.
IComparable =
interface
function CompareTo(Other: TObject): Integer;
end;
ECompareException =
class(
Exception);
TSomeRecord =
class(TInterfacedObject, IComparable)
private
FSomeInt: Integer;
FSomeString:
String;
public
constructor Create(Str:
String; Int: Integer);
function CompareTo(Other: TObject): Integer;
published
property SomeString:
String read FSomeString
write FSomeString;
property SomeInt: Integer
read FSomeInt
write FSomeInt;
end;
TForm1 =
class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private-Deklarationen }
public
{ Public-Deklarationen }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TSomeRecord }
function TSomeRecord.CompareTo(Other: TObject): Integer;
begin
if (Other
is TSomeRecord)
then begin
Result := Self.SomeInt - TSomeRecord(Other).SomeInt;
end else begin
raise ECompareException.Create(EmptyStr);
end;
end;
constructor TSomeRecord.Create(Str:
String; Int: Integer);
begin
inherited Create;
FSomeInt := Int;
FSomeString := Str;
end;
//Beispiel
procedure TForm1.Button1Click(Sender: TObject);
var
Rec1, Rec2: TSomeRecord;
Rel:
String;
begin
Rec1 := TSomeRecord.Create('
Do you have', Random(100));
Rec2 := TSomeRecord.Create('
stairs in your house?', Random(100));
try
case Rec1.CompareTo(Rec2)
of
-MaxInt..-1: Rel := '
< ';
0: Rel := '
= ';
1..MaxInt: Rel := '
> ';
end;
Button1.Caption := IntToStr(Rec1.SomeInt) + Rel + IntToStr(Rec2.SomeInt);
finally
Rec1.Free;
Rec2.Free;
end;
end;
end.