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

发布于 2024-10-20 18:25:41 字数 161 浏览 2 评论 0原文

我的应用程序使用 XmlSerializer 保存一个类,然后在需要时通过再次反序列化来创建一个实例。 我想在构造函数逻辑中使用类的一些属性成员(在反序列化期间分配)。可以假设首先分配属性,然后分配所有属性后是否会调用构造函数?

继续这个主题,是否有关于反序列化期间发生的事件顺序的任何文档?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

对你的占有欲 2024-10-27 18:25:41

不,假设构造函数运行时将设置属性是不行的。事实恰恰相反。构造函数是创建对象实例时运行的第一段代码。在构造函数开始执行之前,无法设置属性。

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

  • 调用无参数构造函数
  • 将属性设置为其反序列化值

解决此问题的方法是使用工厂方法进行反序列化,然后运行取决于所设置的属性的逻辑。例如

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

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;
  }
}
酒中人 2024-10-27 18:25:41

构造函数是对象的创建。您的对象需要在分配属性值之前创建。然后,构造函数将首先被调用。

我不知道该序列的任何文档。但是,如果您的类不是那么大,则可以添加一些断点,您将看到哪些事件是第一个。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文