【问题标题】:How do I set Xml serialization attributes per instance (or per type) with generic classes如何使用泛型类为每个实例(或每个类型)设置 Xml 序列化属性
【发布时间】:2011-10-06 19:47:57
【问题描述】:

我有一个像这样的类(更复杂,但对示例进行了简化):

public class MyClass {
   public MyClass() { }

   [XmlAttribute("somename")]
   public String MyString { get; set; }

   [XmlElement("AString")]
   public List<String> TheList { get; set; }

   // Other uninteresting methods and private members.
}

Xml 序列化工作正常。我想做的(如果不是太疯狂的话)是改变这个类以使用泛型,这样我就可以让“TheList”使用不同的类型。我想要的是能够以某种方式为每个实例(或每个类型)指定 XmlElement 名称。

理想的情况是在创建实例时设置名称。在创建时宏替换属性参数字符串会很好,但我不知道是否有任何类似的可能。也许它看起来像:

public class MyClass<T, (MagicalMacro)> {
   // Some kind of constructor, methods, whatever as needed.
   // MyString as above.

   [XmlElement(MagicalMacro)] // This does not compile.
   public List<T> TheList { get; set; }

   // Etc.
}
...
MyClass<int, (MagicalMacro)> myClass = new MyClass<int, "AnInteger">();

不太理想但仍然令人满意的是根据 T 的类型命名“TheList”输出名称。

public class MyClass<T> {
   // Same constructor and MyString as the first example.

   [XmlElement(typeof(T).Name)] // This does not compile - string not constant.
   public List<T> TheList { get; set; }

   // Etc.
}

谢谢。

【问题讨论】:

    标签: c# generics attributes xml-serialization


    【解决方案1】:

    属性需要文字。解决这个问题的方法是使用XmlAttributeOverrides 在运行时配置它,并将其传递给XmlSerializer 构造函数。但是:当你这样做时缓存并重新使用序列化程序实例,否则你会泄漏动态生成的程序集。

    【讨论】:

    • 在运行时需要这样做让我感到困惑的是,我在编译时拥有我需要的所有信息。我可以使用文字,我只需要根据所使用的泛型类型将其设置为不同。除了可能使用的每个新类型的“XmlElement”属性之外,复制类中的所有内容似乎非常不雅。这破坏了泛型的用处。
    • @Steven - 相反 - 泛型的意义在于你对每个 T 做 相同的事情,而不是对每个 T 进行专门化。字面意思是 常量文字,而不是解析恰好来自文字的值的表达式。
    • @Steven 如果你发现属性太有限,你总是可以通过泛型和 typeof(T) 进行 XAO 设置和序列化缓存
    • 在我看来,专门如何根据其类型序列化为 xml 将非常普遍,即使它只是更改 xml 标签。对于不同的类型,代码完全相同——只是属性需要更改。我现在有 10 个不同的类,填充了完全相同的代码,除了每个文件有 1 个属性和管理类型一致性的噩梦。如果我想聪明一点,我可能会将 一些 代码移动到基类中,但我仍然有 10 种类型,以便我可以指定不同的 xml 标记。 XmlAttributeOverrides 对我不起作用。
    • @Steven 它应该...我现在很忙(这不是一个小例子),但我可能会看看我可以做到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    • 2023-03-03
    • 2010-11-24
    • 1970-01-01
    相关资源
    最近更新 更多