Setting the initial value of a property when using DataContractSerializer

后端 未结 2 1511
野性不改
野性不改 2021-01-17 16:07

If I am serializing and later deserializing a class using DataContractSerializer how can I control the initial values of properties that were not serialized?

相关标签:
2条回答
  • 2021-01-17 16:46

    Actually the correct way of doing it is by using the OnDeserializing attribute (notice the "ing" suffix). The method marked with this attribute is called before the member values are deserialized.

    0 讨论(0)
  • You can use a serialization callback. Add the following method to your Person class:

    [OnDeserialized]
    void OnDeserialized(StreamingContext context)
    {
        this.IsNew = true;
    }
    

    Another option is to remove the [DataContract] and [DataMember] attributes. In this case DCSerializer will call your constructor when it deserializes.

    0 讨论(0)
提交回复
热议问题