Delphi TList<T> generics
Asked Answered
E

1

5

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)

Ewers answered 26/10, 2014 at 23:48 Comment(0)
S
8

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..
Sendal answered 27/10, 2014 at 0:28 Comment(2)
Thanks, that's very useful. One last thing, can you give me an example of an IComparer function to use with this different type of objectlist? the usual functions don't work with this. (for .sort)Ewers
@Ewers #13252669Windburn

© 2022 - 2024 — McMap. All rights reserved.