XmlSerializer的可以反序列化到一个可空< INT&GT ;? [英] Can XmlSerializer deserialize into a Nullable<int>?

查看:901
本文介绍了XmlSerializer的可以反序列化到一个可空< INT&GT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是重复的<一个href=\"http://stackoverflow.com/questions/306877/can-xmlserializer-deserialize-into-a-nullableint\">http://stackoverflow.com/questions/306877/can-xmlserializer-deserialize-into-a-nullableint但我需要一个解决方案,既没有改变的xml文件,也没有强迫我实现的IXmlSerializable接口。我不想要实现IXmlSerializable的,因为我有很多的旁边附加元素&LT;号>那得到正确反序列化

This is duplicate of http://stackoverflow.com/questions/306877/can-xmlserializer-deserialize-into-a-nullableint but I need a solution that neither change xml document nor forces me to implement IXmlSerializable interface. I dont want to implement IXmlSerializable because I have many additional elements beside <number> that get deserialized correctly.

我的XML可以包含的元素&LT;数&GT; 4℃; /数字&GT; &LT;数/&GT;

My xml can contain either element <number>4</number> or <number/>

<root>
...
either <number>4</number> or <number/>
... [other elements]
</root>

public class root
{
public int? number {get; set;}
...
}

不起作用。

推荐答案

您可以只使用一个替代属性。

You can just use a surrogate property.

public class MyType1
{
    // XmlIgnore means it is not directly serialized
    [XmlIgnore]
    public int? number
    {
        get; set;
    }

    // acts as a surrogate for the nullable property
    [XmlElement("number")]
    public string _number_Surrogate
    {
        get
        {
            return (number.HasValue) ? number.ToString() : "";
        }
        set
        {
            if (!value.Equals(""))
            {
                number = Int32.Parse(value);
            }
        }
    }

    public System.DateTime Time
    {
        get; set;
    }
}

这篇关于XmlSerializer的可以反序列化到一个可空&LT; INT&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆