XmlSerializer 和可为 null 的属性
我有一堂课有很多 Nullable
[XmlIgnore] public int? Age { get { return this.age; } set { this.age = value; } } [XmlAttribute("Age")] public int AgeValue { get { return this.age.Value; } set { this.age = value; } } [XmlIgnore] public bool AgeValueSpecified { get { return this.age.HasValue; } }
效果很好 - 如果“Age”属性有值,它会被序列化为属性。如果它没有值,则不会序列化。
问题是,正如我提到的,我的类中有很多 Nullable,而这种模式只会让事情变得混乱且难以管理。
我希望有一种方法可以使 Nullable 对 XmlSerializer 更加友好。或者,如果做不到这一点,有一种方法可以创建一个可空替换。
有谁知道我该如何做到这一点?
谢谢。
I have a class with numerous Nullable<T> properties which I want to be serializable to XML as attributes. This is apparently a no-no as they are considered 'complex types'. So, instead I implement the *Specified pattern, where I create an addition *Value and *Specified property as follows:
[XmlIgnore] public int? Age { get { return this.age; } set { this.age = value; } } [XmlAttribute("Age")] public int AgeValue { get { return this.age.Value; } set { this.age = value; } } [XmlIgnore] public bool AgeValueSpecified { get { return this.age.HasValue; } }
Which works fine - if the 'Age' property has a value, it is serialized as an attribute. If it doesn't have a value, it isn't serialized.
The problem is that, as I mentioned, a have a lot of Nullable-s in my class and this pattern is just making things messy and unmanageable.
I'm hoping there is a way to make Nullable more XmlSerializer friendly. Or, failing that, a way to create a Nullable replacement which is.
Does anyone have any ideas how I could do this?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我正在处理的一些代码也遇到了类似的问题,我决定只对我正在序列化和反序列化的属性使用字符串。我最终得到了这样的结果:
I had a similar problem with some code I was working on, and I decided just to use a string for the property I was serializing and deserializing. I ended up with something like this:
在您的类上实现
IXmlSerialized
接口。然后,您可以处理特殊情况,例如ReadXML
和WriteXML
方法中的可空值。 MSDN 文档页面中有一个很好的示例。。Implement the
IXmlSerializable
interface on your class. You can then handle special cases such as nullables in theReadXML
andWriteXML
methods. There's a good example in the MSDN documentation page..