XmlSerializer的和可空属性

编程入门 行业动态 更新时间:2024-10-11 09:28:47
本文介绍了XmlSerializer的和可空属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一类与众多可空< T>我想序列化到XML的属性的属性。这显然​​是一个没有没有,因为他们被认为是复杂类型。所以,相反,我实现了*指定的模式,我在那里创造的附加价值*和*指定属性如下:

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.

我希望有一种方法,使可空更XmlSerializer的友好。或者,如果做不到这一点,一种方式来创建一个可空更换在。

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?

感谢。

推荐答案

实现您的类的IXmlSerializable 接口。然后,您可以处理特殊情况,例如在 ReadXML的和中WriteXML 方法nullables。 There's一个很好的例子,在MSDN文档页面。的。

Implement the IXmlSerializable interface on your class. You can then handle special cases such as nullables in the ReadXML and WriteXML methods. There's a good example in the MSDN documentation page..

class YourClass : IXmlSerializable { public int? Age { get { return this.age; } set { this.age = value; } } //OTHER CLASS STUFF// #region IXmlSerializable members public void WriteXml (XmlWriter writer) { if( Age != null ) { writer.WriteValue(writer) } } public void ReadXml (XmlReader reader) { Age = reader.ReadValue(); } public XmlSchema GetSchema() { return(null); } #endregion }

更多推荐

XmlSerializer的和可空属性

本文发布于:2023-11-06 03:28:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562610.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   XmlSerializer

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!