您可以使用
ShouldSerialize{PropertyName}告诉XmlSerializer是否应序列化成员的模式来创建函数。例如,如果您的类属性被调用,
MyNullableInt您可能拥有
public bool ShouldSerializeMyNullableInt() { return MyNullableInt.HasValue;}这是一个完整的样本
public class Person{ public string Name {get;set;} public int? Age {get;set;} public bool ShouldSerializeAge() { return Age.HasValue; }}用以下代码序列化
Person thePerson = new Person(){Name="Chris"};XmlSerializer xs = new XmlSerializer(typeof(Person));StringWriter sw = new StringWriter();xs.Serialize(sw, thePerson);以下XML的结果-注意没有年龄
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Name>Chris</Name></Person>



