program Project1;
{$AppType Console}
uses
SysUtils,
Generics.Collections,
Generics.Defaults;
type
TMyObject =
class
strict private
FValue: Integer;
public
property Value: Integer
read FValue
write FValue;
end;
TMyComparer =
class(TComparer<TMyObject>, IComparer<TMyObject>)
function Compare(
const Left, Right: TMyObject): Integer;
end;
TMyObjectList =
class(TObjectList<TMyObject>)
public
constructor Create;
function IndexOfValue(
const Value: Integer): Integer;
end;
{ TMyComparer }
function TMyComparer.Compare(
const Left, Right: TMyObject): Integer;
begin
Result := Left.Value - Right.Value;
end;
{ TMyObjectList }
constructor TMyObjectList.Create;
begin
inherited Create(TMyComparer.Create);
end;
function TMyObjectList.IndexOfValue(
const Value: Integer): Integer;
var
Temp: TMyObject;
begin
Temp := TMyObject.Create;
try
Temp.Value := Value;
Result := IndexOf(Temp);
finally
Temp.Free;
end;
end;
{ Hauptprogramm }
var
MyObjectList: TMyObjectList;
MyObject: TMyObject;
Index: Integer;
begin
try
MyObjectList := TMyObjectList.Create;
try
for Index := 9
downto 0
do
begin
MyObject := TMyObject.Create;
MyObject.Value :=
Index;
MyObjectList.Add(MyObject);
end;
for Index := -1
to 10
do
WriteLn(Format(
'
MyObjectList.IndexOfValue(%3d) = %3d',
[
Index, MyObjectList.IndexOfValue(
Index)]
));
ReadLn;
finally
MyObjectList.Free;
end;
except
on E:
Exception do
WriteLn(E.ClassName, '
: ', E.
Message);
end;
end.