views:

396

answers:

1

Hi,

How can I store generics in a generics TList holded by a non generic object ?

type
  TXmlBuilder = class
  type
    TXmlAttribute<T>= class
      Name: String;
      Value: T;
    end;

    TXmlNode = class
      Name: String;
      Attributes: TList<TXmlAttribute<T>>;
      Nodes: TList<TXmlNode>;
    end;
  ...
  end;

The compiler says T is not delcared in

Attributes: TList<TXmlAttribute<T>>;

-- Pierre Yager

+1  A: 

TXmlNode doesn't know what T is. What is it supposed to be?

Maybe you meant:

TXmlNode<T> = class
  Name: String;
  Attributes: TList<TXmlAttribute<T>>;
  Nodes: TList<TXmlNode<T>>;
end;

... either that, or you need to specify a type.

However, it seems you're missing something here. Generics allow you to create a separate class for each type -- not a class for all types. In the code above, TList holds an array of types that are the same, and you probably want them different. Consider this instead:

  TXmlBuilder = class
  type
    TXmlAttribute= class
      Name: String;
      Value: Variant;
    end;

    TXmlNode = class
      Name: String;
      Attributes: TList<TXmlAttribute>;
      Nodes: TList<TXmlNode>;
    end;
  ...
  end;
Kornel Kisielewicz
Thank you, I understand that I can't store generics in a generic list because the stored type has to be known at compile time. Thank for your suggestion about using variants but as I'm writing a (de)serializer for native delphi types to/from xml, i would prefer using the new TValue from Rtti if possible.
ZeDalaye
@ZeDalaye: if that's what you want to do, then make sure to also read this: http://stackoverflow.com/questions/368913/whats-a-good-way-to-serialize-delphi-object-tree-to-xml-using-rtti-and-not-cust
Wouter van Nifterick