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

时光总嘲笑我的痴心妄想 提交于 2019-12-21 03:46:11

问题


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 my class (assigned during deserialisation) in my constructor logic. It is ok to assume that the properties will be assigned first, and once all properties are assigned will the constructor be called?

Continuing on this topic, is there any documentation available on the sequence of events that take place during deserialisation?


回答1:


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;
  }
}



回答2:


The constructor is the creation of your object. Your object need to be created before assign properties value. Then, the constructor will be called first.

I don't know any documentation for the sequence. But if your class isn't so big, it's possible to add some breakpoint and you'll see which events is first.



来源:https://stackoverflow.com/questions/5198431/when-is-the-class-constructor-called-while-deserialising-using-xmlserializer-des

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!