When is the class constructor called while deserialising using XmlSerializer.Deserialize?

前端 未结 2 2123
甜味超标
甜味超标 2021-02-13 22:01

My application saves a class away using XmlSerializer, and then later when required, creates an instance by deserialising it again. I would like to use some property members of

2条回答
  •  生来不讨喜
    2021-02-13 22:28

    No it is not OK to assume the properties will be set when the constructor runs. The opposite is true. The constructor is the very first piece of code which runs when an instance of an object is created. It's not possible for the properties to be set until after the constructor has started executing.

    The XML deserialization process roughly looks like the following

    • Call the parameterless constructor
    • Set the properties to their deserialized values

    A way to work around this is to use a factory method to do the deserialization and then run the logic which depends on the properties being set. For example

    class MyClass {
      ...
      public static MyClass Deserialize(string xmlContents) {
        var local = ... // Do the XML deserialization
        local.PostCreateLogic();
        return local;
      }
    }
    

提交回复
热议问题