How to tell XmlSerializer to serialize properties with [DefautValue(…)] always?

后端 未结 4 1543
孤街浪徒
孤街浪徒 2020-12-20 11:42

I am using DefaultValue attribute for the proper PropertyGrid behavior (it shows values different from default in bold). Now if I want to serialize

4条回答
  •  旧时难觅i
    2020-12-20 12:38

    As long as you don't need attributes in your Xml, if you use the DataContractSerializer instead you will get the behavior you desire.

    [DataContract]
    public class Test
    {
        [DataMember]
        [DefaultValue(false)]
        public bool AllowNegative { get; set; }
    }
    
    void Main()
    {
        var sb2 = new StringBuilder();
        var dcs = new DataContractSerializer(typeof(Test));
    
        using(var writer = XmlWriter.Create(sb2))
        {
            dcs.WriteObject(writer, new Test());
        }
    
        Console.WriteLine(sb2.ToString());  
    }
    

    produces (minus namespaces etc)

    
        false
    
    

提交回复
热议问题