DataContractSerializer doesn't call my constructor?

后端 未结 4 1480
感动是毒
感动是毒 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:11

    Use [OnDeserialized] attribute to initialise your properties.

    // This method is called after the object
    // is completely deserialized. Use it instead of the
    // constructror.
    [OnDeserialized]
    void OnDeserialized(StreamingContext context)
    {
        fullName = firstName + " " + lastName;
    }
    

    Please refer to microsoft guid-lines: https://docs.microsoft.com/en-us/dotnet/standard/serialization/serialization-guidelines

提交回复
热议问题