问题描述
这是重复的http://stackoverflow.com/questions/306877/can-xmlserializer-deserialize-into-a-nullableint但我需要一个解决方案,既没有改变的xml文件,也没有强迫我实现的IXmlSerializable接口。我不想要实现IXmlSerializable的,因为我有很多的旁边附加元素<号
>那得到正确反序列化
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 ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!