ZeDalaye
ZeDalaye

Reputation: 709

Delphi 2010 Generics of Generics

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

Upvotes: 2

Views: 1561

Answers (1)

Kornel Kisielewicz
Kornel Kisielewicz

Reputation: 57525

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;

Upvotes: 2

Related Questions