简体   繁体   English

何时使用XmlSerializer.Deserialize进行反序列化时调用类构造函数?

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

My application saves a class away using XmlSerializer, and then later when required, creates an instance by deserialising it again. 我的应用程序使用XmlSerializer保存一个类,然后在需要时通过再次反序列化来创建一个实例。 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? 继续讨论这个主题,是否有关于反序列化过程中发生的事件序列的文档?

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 XML反序列化过程大致如下所示

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

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. 但如果你的课程不是那么大,可以添加一些断点,你会看到哪些事件是第一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM