Home How to use TObjectList for arbitrary class type?
Reply: 0

How to use TObjectList for arbitrary class type?

user2002
1#
user2002 Published in April 26, 2018, 5:14 pm

I'm still a bit fuzzy with generics in Delphi, but have been using TObjectList<> quite widely. Now I have a situation where I have a base class with such a private field, but needs to be created for an arbitrary class, also inherited from another base.

To clarify, I have two base classes:

type
  TItem = class;
  TItems = class;

  TItemClass = class of TItem;

  TItem = class(TPersistent)
  private
    FSomeStuffForAllIneritedClasses: TSomeStuff;
  end;

  TItems = class(TPersistent)
  private
    FItems: TObjectList<TItem>;
    FItemClass: TItemClass;
  public
    constructor Create(AItemClass: TItemClass);
    destructor Destroy; override;
    function Add: TItem;
    ...
  end;

This pair of classes is then further inherited into more specific classes. I'd like the object list to be shared for all of them, while each holds actually a different type internally.

type
  TSomeItem = class(TItem)
  private
    FSomeOtherStuff: TSomeOtherStuff;
    ...
  end;

  TSomeItems = class(TItems)
  public
    function Add: TSomeItem; //Calls inherited, similar to a TCollection
    procedure DoSomethingOnlyThisClassShouldDo;
    ...
  end;

Now the problem is when it comes to creating the actual object list. I'm trying to do it like this:

constructor TItems.Create(AItemClass: TItemClass);
begin
  inherited Create;
  FItemClass:= AItemClass;
  FItems:= TObjectList<AItemClass>.Create(True);
end;

However, the code insight complains about this:

Undeclared Identifier AItemClass

Even more, the compiler has yet a different complaint:

Undeclared Identifier TObjectList

Where, I do in fact have System.Generics.Collections used in this unit.

What am I doing wrong here, and how should I do this instead?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.348265 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO