Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi TList<T> generics

Can someone explain to me if this is possible, or I'm completely missunderstanding this Delphi feature.

Let's say I have a class, I create a few of them, and then add them to an ObjectList. Normally I do it like this:

Type TMyClass = class(TObject)
  stuff: string;
..
end;

Var things: TObjectList;

things := TObjectList.Create;
things.Add(TMyClass.Create);

// now I want to access stuff, so I need to typecast the class
TMyClass(things[0]).stuff..

So now my question, is it possible to declare the list in a way where I could just do like.. things[0].stuff and still have access to the the usual TObjectList features like .sort .indexof etc..? (without making a special class for this to simulate the objectlist)

like image 939
hikari Avatar asked Oct 26 '14 23:10

hikari


1 Answers

You are using the TObjectList from System.Contnrs, which manages a list of pointers.

You want TObjectList from System.Generics.Collections. I know, using the same name can be a little confusing.

Type TMyClass = class(TObject)
  stuff: string;
..
end;

Var things: TObjectList<TMyCLass>;

things := TObjectList<TMyCLass>.Create;
things.Add(TMyClass.Create);

things[0].stuff..
like image 65
Bruce McGee Avatar answered Oct 17 '22 03:10

Bruce McGee