Peter Turner
Peter Turner

Reputation: 11435

Converting TObjectList ancestor to generic collection in Delphi

I've got a class

TMyAwesomeList = class(TObjectList)

which holds

 TAwesomeItem = class(TPersistent)

where TAwesomeItem is pretty much an abstract class for

 TAwesomeItem1 = class(TAwesomeItem)
 TAwesomeItem2 = class(TAwesomeItem)
 TAwesomeItem3 = class(TAwesomeItem)
 TAwesomeItem3a = class(TAwesomeItem3)

and so on (about 30 subclasses where there are a few intermediate abstract classes) that accomplish some object relational modeling I implemented a year ago in anticipation of finally converting from Delphi 7 to 2009 (and soon XE2).

The code still works in Delphi 2009, but I want to do a

 for AwesomeItem3a in AwesomeList do
 begin     
    //something awesome
 end;

and I don't know how to go about restructuring the TMyAwesomeList (or adding several subclasses) to make this work.

Upvotes: 3

Views: 952

Answers (1)

Ondrej Kelle
Ondrej Kelle

Reputation: 37221

Based on your comments, it seems you can simply use TObjectList directly.

var
  MyAwesomeList1: TObjectList<TMyAwesomeItem1>;
  MyAwesomeItem1: TMyAwesomeItem1;
begin
  MyAwesomeList1 := TObjectList<TMyAwesomeItem1>.Create;
  try
    // populate the list...

    for MyAwesomeItem1 in MyAwesomeList1 do
      ...
  finally
    MyAwesomeList1.Free;
  end;
end;

... and same for TMyAwesomeItem2, etc. If you prefer, you can also declare a type alias:

type
  TMyAwesomeList1 = TObjectList<TMyAwesomeItem1>;
  TMyAwesomeList2 = TObjectList<TMyAwesomeItem2>;
  // etc.

Upvotes: 7

Related Questions