我有一个包含大量 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; } }
效果很好——如果“年龄”属性有值,它会被序列化为一个属性。如果它没有值,则不会序列化。
问题是,正如我提到的,我的类(class)中有很多 Nullable-s,这种模式只会让事情变得困惑和难以管理。
我希望有一种方法可以使 Nullable 对 XmlSerializer 更加友好。或者,如果失败了,一种创建 Nullable 替换的方法是。
有人知道我该怎么做吗?
谢谢。
最佳答案
我在处理一些代码时遇到了类似的问题,因此我决定只对我正在序列化和反序列化的属性使用一个字符串。我最终得到了这样的结果:
[XmlAttribute("Age")]
public string Age
{
get
{
if (this.age.HasValue)
return this.age.Value.ToString();
else
return null;
}
set
{
if (value != null)
this.age = int.Parse(value);
else
this.age = null;
}
}
[XmlIgnore]
public int? age;
关于c# - XmlSerializer 和可为空的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3250706/