XmlSerializer的和可空属性

XmlSerializer的和可空属性

本文介绍了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的和可空属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 14:34