Enable. NET xml serialization to support Nullable and nullable serialization.
. For the sequence of net, we all pass xsd.exe for the generation of contract classes. The null judgment of value types is determined by declaring the bool attribute of the same name + Specified, for example:
public class Person { public string Name { get; set; } public int Age { get; set; }
[XmlIgnore] public bool AgeSpecified { get; set; } }
In this way, to generate an Age node, you must set AgeSpecified = true in addition to assigning values to the Age. During deserialization, you can determine whether the Age attribute is assigned a value by determining whether the AgeSpecified is true. Well, although it is troublesome, it is quite good to solve the problem, and it is generated by xsd for us to save time. But what if you want the Person class to support xml serialization and json serialization? How do you deal with this Specified field?
Someone might ask, why don't we directly define the Age as a null type? You can try. The serialized xml is as follows:
<?xml version="1.0" encoding="utf-8"?><Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Name>name</Name> <Age xsi:nil="true" /></Person>
I did not assign values to the Age attribute, but generated the Age xsi... Such a wonderful node.
Today, I strolled around the Internet and accidentally found that I could do this:
public class Person { public string Name { get; set; } public int? Age { get; set; } public bool ShouldSerializeAge() { return Age != null; } }
The ShouldSerialize feature exists. If it can be integrated into xsd, it would be nice. Otherwise, to support nullable, all value types will be too tired.
Https://msdn.microsoft.com/en-us/library/53b8022e (v = vs.110). aspx