DefaultValue 会影响序列化,就好像在运行时属性的值与 DefaultValue 所说的相匹配,然后 XmlSerializer 实际上不会写出该元素(因为它是默认值)。
我不确定它是否会影响读取时的默认值,但在快速测试中似乎不会这样做。在您的场景中,我可能只是将其设置为具有支持字段的属性,该属性具有使其“真实”的字段初始化程序。恕我直言,我比 ctor 方法更喜欢这种方法,因为它将它与您为课程定义或未定义的 ctor 分离,但这是相同的目标。
using System;
using System.ComponentModel;
using System.Xml.Serialization;
using System.IO;
class Program
{
static void Main(string[] args)
{
var serializer = new XmlSerializer(typeof(Testing));
string serializedString;
Testing instance = new Testing();
using (StringWriter writer = new StringWriter())
{
instance.SomeProperty = true;
serializer.Serialize(writer, instance);
serializedString = writer.ToString();
}
Console.WriteLine("Serialized instance with SomeProperty={0} out as {1}", instance.SomeProperty, serializedString);
using (StringReader reader = new StringReader(serializedString))
{
instance = (Testing)serializer.Deserialize(reader);
Console.WriteLine("Deserialized string {0} into instance with SomeProperty={1}", serializedString, instance.SomeProperty);
}
Console.ReadLine();
}
}
public class Testing
{
[DefaultValue(true)]
public bool SomeProperty { get; set; }
}
正如我在评论中提到的,xml 序列化属性页面 (http://msdn.microsoft.com/en-us/library/83y7df3e.aspx) 声称 DefaultValue 确实会使序列化程序设置值当它丢失时,但在此测试代码中没有这样做(类似于上面,但只是反序列化 3 个输入)。
using System;
using System.ComponentModel;
using System.Xml.Serialization;
using System.IO;
class Program
{
private static string[] s_inputs = new[]
{
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Testing xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" />",
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Testing xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<SomeProperty />
</Testing>",
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Testing xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<SomeProperty>true</SomeProperty>
</Testing>",
};
static void Main(string[] args)
{
var serializer = new XmlSerializer(typeof(Testing));
foreach (var input in s_inputs)
{
using (StringReader reader = new StringReader(input))
{
Testing instance = (Testing)serializer.Deserialize(reader);
Console.WriteLine("Deserialized string \n{0}\n into instance with SomeProperty={1}", input, instance.SomeProperty);
}
}
Console.ReadLine();
}
}
public class Testing
{
[DefaultValue(true)]
public bool SomeProperty { get; set; }
}