如何在WCF中使用自定义序列化或反序列化来强制datacontact的每个属性上的新实例?

我有一个datacontact,其中有许多成员都有自定义类

如果反序列化时属性为null,我想强制一个新实例。

有没有办法做到这一点?

如果您正在使用DataContract序列化,则可以使用OnDeserialized属性覆盖其默认行为。

从MSDN : 应用于方法时,指定在对象图中对象的反序列化期间调用该方法。 反序列化相对于图中其他对象的顺序是非确定性的。

这是我的示例代码:

 namespace MySpace { public class MyCustomClass { public string MyStrData { get; set; } } [DataContract] public class Data { [DataMember] public int mInt; [DataMember] public MyCustomClass MyCustonObj; [OnDeserialized] void OnDeserialized(StreamingContext c) { if (MyCustonObj == null) { MyCustonObj = new MyCustomClass(); MyCustonObj.MyStrData = "Overridden in serialization"; } } [OnDeserializing] void OnDeserializing(StreamingContext c) { if (MyCustonObj == null) { MyCustonObj = new MyCustomClass(); MyCustonObj.MyStrData = "Overridden in deserializing"; } } [OnSerialized] void OnSerialized(StreamingContext c) { // if you wan to do somehing when serialized here or just remove them } [OnSerializing] void OnSerializing(StreamingContext c) { // if you wan to do somehing during serializing here or just remove them } } } [ServiceContract] public interface IService { [OperationContract] Data Method(Data dd); } public class Service : IService { public Data Method(Data dd) { return dd; } } class Program { static void Main(string[] args) { string Url = "http://localhost:8000/"; Binding binding = new BasicHttpBinding(); ServiceHost host = new ServiceHost(typeof(Service)); host.AddServiceEndpoint(typeof(IService), binding, Url); host.Open(); ChannelFactory fac = new ChannelFactory(binding); fac.Open(); IService proxy = fac.CreateChannel(new EndpointAddress(Url)); Data d = new Data(); d.mInt = 5; Console.WriteLine("Data before calling service " + d.mInt); Console.WriteLine("Data before calling service " + (d.MyCustonObj == null ? "null" : d.MyCustonObj.MyStrData)); d = proxy.Method(d); fac.Close(); host.Close(); Console.WriteLine("Data after calling service " + d.mInt); Console.WriteLine("Data after calling service " + d.MyCustonObj.MyStrData); Console.ReadLine(); } }