views:

82

answers:

1

I'm creating a generic list class that has a member of type Array(Array of ). The problem is the class destruction,because the class is supposed to be used for types from byte to types inheriting TObject.

Specifically:

destructor Destroy;
var elem:T;
begin
  /*if(T is Tobject) then  //Check if T inherits TObject {Compiler error!}
    for elem in FData do TObject(elem).Free;*/    // do not know how to do it

  SetLength(FItems,0); //FItems : Array of T
  inherited Destroy;
end;

How do I check if T is TObject so I can free every member if the typeidenitifier is a class,for example?

+2  A: 

You can get the type info of your type T with the TypeInfo compiler magic function. It returns a pointer which you can cast to PTypeInfo, which is declared in the TypInfo unit. So:

if PTypeInfo(typeInfo(T)).Kind = tkClass then
  //do whatever
Mason Wheeler
Do you know how can I tell the compiler that it is TObject? TObject(elem).Free; gives next error.I also tried with TObject(Fitems[i]).Free ,but still the same error - Invalid typecast.Do you know it or should I start a new question?
John
Not sure, but what I would do is avoid this altogether by making a separate object version. Take a look at `TList<T>` and `TObjectList<T>` in Generics.Collections to see how it's done.
Mason Wheeler