[fpc-pascal]Dynamic array of objects
memsom at interalpha.co.uk
memsom at interalpha.co.uk
Fri May 30 11:46:15 CEST 2003
> Hi, I need something like a dynamic array of objects,
> easy to manipulate each object and field. Is TStream
> and TCollection what I need, or maybe TList is enough,
> maybe another Type?
Jordi,
the unit called 'contnrs' has a TObjectList class. I would advocate it's use.
The main reason is that you can construct a TObjectList like so:
MyObjectList := TObjectList.Create(True);
and this then means that the TObjectList 'owns' all objects added to it, and it
will free then when they are deleted without you having to do any work
yourself...
MyObjectList.Delete( idx );
//same as
var
tmp: TObject;
begin
tmp := TObject ( MyList[idx] );
try
MyList.Delete(idx);
finally
tmp.free;
{ might also need the line 'MyList.Pack;'}
end;
end;
You can extend it or wrap it to allow you classes to be accessed directly, but
something like:
var
tmp: TMyClass;
idx: integer;
begin
tmp := TMyClass.Create;
tmp.SomeStringField := 'test';
idx := MyObjectList.Add(tmp);
//accessing the stored class...
writeln( TMyClass( MyObjectList.Objects[idx] ).SomeStringField );
//or with type checking
writeln( ( MyObjectList.Objects[idx] as TMyClass ).SomeStringField );
//verifying that the class is of type TMyClass or Descends from it
if ( MyObjectList.Objects[idx] is TMyClass ) then
writeln( 'it is a TMyClass and it''s actual class type is ',
TMyClass( MyObjectList.Objects[idx] ).ClassName );
//^^^ no need for 'as' because we know it *is* a TMyClass
// or descendent instance.
end;
The one thing I do suggest is not mixing unrelated classes in the list. Classes
that all descend from a base class are fine, but putting unrelated TObject
descendents in the same list can make juggling the type casting a little more
work. It's better to have a base class with common functionality that you
override in the decendents than disparate classes. You may need to reengineer
some things, or to use multiple lists, but it will work out better in the long
run imho.
There is also a TComponentList and a TClassList and a TInterfaceList too. All
with similar properties.
Hope that helps...
Matt
---------------------------------------------
This message was sent using Mistral WebMail.
http://www.mistral.co.uk/
More information about the fpc-pascal
mailing list