How to make a value type nullable with .NET XmlSerializer?

前端 未结 7 507
陌清茗
陌清茗 2020-12-02 11:47

Let\'s suppose I have this object:

[Serializable]
public class MyClass
{
    public int Age { get; set; }
    public int MyClassB { get; set; }
}
[Serializab         


        
7条回答
  •  自闭症患者
    2020-12-02 11:54

    Extending Samuel's answer and Greg Beech's comment to the case of a boolean property: if the property is of type bool then you can't write a simple test in the propertySpecified property.

    A solution is to use a Nullable type, then the test in the propertySpecified property is simply property.HasValue. e.g.

    using System.Xml.Serialization;
    
    public class Person
    {
        public bool? Employed { get; set; }
    
        [XmlIgnore]
        public bool EmployedSpecified { get { return Employed.HasValue; } }
    }
    

    An alternative to using a nullable type for a numeric property (suggested by Greg Beech) is to set the value property to an invalid default value, such as -1, as follows:

    using System.ComponentModel;
    using System.Xml.Serialization;
    
    public class Person
    {
        [DefaultValue(-1)]
        public int Age { get; set; }
    
        [XmlIgnore]
        public bool AgeSpecified { get { return Age >= 0; } }
    }
    

提交回复
热议问题