.NET数据契约DataContract提供4个事件
[OnDeserialized|OnDeserializing|OnSerialized|OnSerializing]
我们可以通过以上事件在序列化或反序列化时实现构造函数的功能
[DataContract] public class TestInfo { [DataMember(Name = "t1")] public int Test1{ get; set; } [DataMember(Name = "t2")] public string Test2{ get; set; } [OnDeserialized] void OnDeserialized(StreamingContext context) { if (this.Test2 == null) this.Test2 = "deserialized"; } [OnSerializing] void OnSerializing(StreamingContext context) { if (this.Test2 == null) this.Test2 = "serializing"; } }