DataContractSerializer doesn't call my constructor?

后端 未结 4 1482
感动是毒
感动是毒 2020-11-27 14:49

I just realized something crazy, which I assumed to be completely impossible : when deserializing an object, the DataContractSerializer doesn\'t call the constructor

4条回答
  •  醉酒成梦
    2020-11-27 15:34

    In my case, i wanted to create an object to use in a lock-clause. I tried implementing IDeserializationCallback (didn't work because callback only runs after properties have been assigned), [OnDeserialized] (didn't work, same previous reason), and ISerializable (didn't work because the class is decorated with the [DataContractAttribute]).

    My workaround was to initialize the field before it's used using Interlocked.CompareExchange. A bit of unnecessary work gets done, but at least now my field gets initialized when a DataContractSerializer creates it.

    Interlocked.CompareExchange(ref _sync, new object(), null);
    

提交回复
热议问题