同义的属性名与XmlAttribute
问题描述:
我们的XML格式已经从同义的属性名与XmlAttribute
<foo bar="xyz" />
改为
<foo abc="xyz" />
。请注意属性名称从bar更改为abc。
是否可以同时使用XmlAttribute
支持两个属性名称?
我试着用XmlAttribute
两次标记类成员,但是这会导致编译时错误。
public sealed class Foo {
[XmlAttribute("bar")] // Error: The attribute `System.Xml.Serialization.XmlAttributeAttribute' cannot be applied multiple times
[XmlAttribute("abc")]
public string bar;
}
不知道如何处理同义词,而无需编写自定义反序列化整个富类属性的名称?
答
找到带有吸气的方式,但这不是最好的解决办法:
public sealed class Foo {
// Both have to be public, otherwise they don't get deserialized
[XmlAttribute("bar"), DefaultValue(null)]
public string _bar;
[XmlAttribute("abc"), DefaultValue(null)]
public string _abc;
public string bar {
get {
if (_bar != null) {
return _bar;
} else {
return _abc;
}
}
}
}
的缺点是,这两个_bar
和_abc
现在富的公共API的一部分。此外,我不能宣称两者都必须存在。