使用 XmlSerializer.Deserialize 反序列化时何时调用类构造函数?
我的应用程序使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,假设构造函数运行时将设置属性是不行的。事实恰恰相反。构造函数是创建对象实例时运行的第一段代码。在构造函数开始执行之前,无法设置属性。
XML 反序列化过程大致如下所示
解决此问题的方法是使用工厂方法进行反序列化,然后运行取决于所设置的属性的逻辑。例如
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
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
构造函数是对象的创建。您的对象需要在分配属性值之前创建。然后,构造函数将首先被调用。
我不知道该序列的任何文档。但是,如果您的类不是那么大,则可以添加一些断点,您将看到哪些事件是第一个。
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.