2010-01-26 85 views
2

如何将泛型保存在非泛型对象的泛型TList中?Delphi 2010泛型的泛型

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; 

编译器说,T没有在

Attributes: TList<TXmlAttribute<T>>; 

delcared - 皮埃尔雅格尔

回答

2

TXmlNode不知道T是什么。它应该是什么?

也许你的意思是:

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

...要么,或者你需要指定一个类型。

但是,看起来你在这里错过了一些东西。泛型允许您为每种类型创建一个单独的类 - 不是所有类型的类。在上面的代码中,TList拥有一组相同的类型,并且您可能希望它们与不同。考虑这个,而不是:

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

    TXmlNode = class 
     Name: String; 
     Attributes: TList<TXmlAttribute>; 
     Nodes: TList<TXmlNode>; 
    end; 
    ... 
    end; 
TXmlBuilder = class 
    type 
    TXmlAttribute= class 
     Name: String; 
     Value: Variant; 
    end; 

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

谢谢,我明白我不能将泛型存储在通用列表中,因为存储类型必须在编译时已知。感谢您使用变体的建议,但由于我正在为xml编写原生delphi类型的(de)序列化程序,如果可能的话,我宁愿使用来自Rtti的新TValue。 – ZeDalaye 2010-01-26 11:45:41

+0

@ZeDalaye:如果这就是你想要做的,那么一定要读这个:http://stackoverflow.com/questions/368913/whats-a-good-way-to-serialize-delphi-object-tree-对XML的使用,RTTI和 - 不卡斯特 – 2010-01-27 10:17:37