WCF反序列化,不会调用构造函数,如何解决类的初始化问题?遇到了这个问题,找了一些资料最终解决了这个问题。关键是两个特性:
[OnDeserializing]
[OnDeserialized]
看一下代码:
[DataContract] public class MyDataType { [DataMember] private List<int> nVal = new List<int>(); public MyDataType() { nVal.Add(12); } [OnDeserializing] void BeginInit(StreamingContext sc) { Console.WriteLine("same to begin Constructor"); } [OnDeserialized] void EndInit(StreamingContext sc) { Console.WriteLine("same to end Constructor"); } [DataMember] public int InitMemberData { get { return 0; } set { object obj = this; Console.WriteLine("InitMemberData: set."); } } private int intv; [DataMember] public int INT { get { return intv; } set { Console.WriteLine("INT: set."); if(nVal == null) intv = value; } } string _str; [DataMember] public string STRING { get { return _str; } set { Console.WriteLine("STRING: set."); _str = value; } } long _long; [DataMember] public long LONG { get { return _long; } set { Console.WriteLine("LONG: set."); _long = value; } } }
反序列化时的输出:
时间: 2024-11-08 10:29:03