In 2009 a new TObjectList was introduced in Generics.Collections, the old TOjectList was still available in the Contnrs unit, but the new one was more strongly typed and you need to specify the class of object the the list will be populated with. This means a reduction in type casting. Here is an example of how to use it:
TMyListClass = class(TObject)
private
FEntries: TObjectList<TMyEntry>;
public
property Entries: TObjectList<TMyEntry> read FEntries write FEntries;
function GetEntry(aIndex: integer):TMyEntry;
constructor Create;
destructor Destroy; override;
end;
implementation
constructor TMyListClass.Create;
begin
inherited Create;
FEntries := TObjectList<TMyEntry>.Create();
end;
destructor TMyListClass.Destroy;
begin
FEntries.Free;
inherited Destroy;
end;
function TMyListClass.GetEntry(aIndex: integer):TMyEntry;
begin
// You don't need to typecast
// Old way
// if (FEntries.Items[aIndex] is TMyEntry) then
// Result (FEntries.Items[aIndex] as TMyEntry;
Result := FEntries.Items[aIndex];
end;
No comments:
Post a Comment