当同时使用XmlSerializer.Deserialize deserialising被称为类的构造函数? [英] When is the class constructor called while deserialising using XmlSerializer.Deserialize?

查看:188
本文介绍了当同时使用XmlSerializer.Deserialize deserialising被称为类的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序可以节省远用XmlSerializer的一类,再后来需要时,再次deserialising它创建一个实例。
我想用我的课的某些属性成员(deserialisation期间分配)在我的构造函数的逻辑。它是确定假设属性将被首先分配,一旦所有属性分配将构造函数被调用?

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?

继续就这一话题,有没有可用的任何文件上deserialisation过程中发生的事件的顺序?

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.

XML的反序列化过程大致如下所示

The XML deserialization process roughly looks like the following


  • 调用参数的构造函数

  • 将属性的反序列化值

要解决这种情况的方法是使用一个工厂方法做反序列化,然后运行取决于属性被设置的逻辑。例如:

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

这篇关于当同时使用XmlSerializer.Deserialize deserialising被称为类的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆