DataContractSerializer的不叫我的构造函数? [英] DataContractSerializer doesn't call my constructor?

查看:260
本文介绍了DataContractSerializer的不叫我的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我才意识到一些疯狂,我认为是完全不可能的:反序列化对象,在的DataContractSerializer不会调用构造函数时

I just realized something crazy, which I assumed to be completely impossible : when deserializing an object, the DataContractSerializer doesn't call the constructor !

取这个类,如:

[DataContract]
public class Book
{
    public Book()
    { // breakpoint here
    }

    [DataMember(Order = 0)]
    public string Title { get; set; }
    [DataMember(Order = 1)]
    public string Author { get; set; }
    [DataMember(Order = 2)]
    public string Summary { get; set; }
}

当我反序列化类的一个对象,断点不会打。我完全不知道它是如何可能的,因为它是此对象的唯一的构造!

When I deserialize an object of that class, the breakpoint is not hit. I have absolutely no idea how it is possible, since it is the only constructor for this object !

我认为是由因为 DataContract 属性的编译器生成也许是一个额外的构造,但我怎么也找不到它通过反射......

I assumed that perhaps an additional constructor was generated by the compiler because of the DataContract attribute, but I couldn't find it through reflection...

所以,我想知道的是:怎么可能我的类的实例,而不被称为??构造函数来创建

So, what I'd like to know is this : how could an instance of my class be created without the constructor being called ??

注:我知道,我可以使用 OnDeserializing 属性初始化我的对象序列化开始时,这不是我的问题的主题

NOTE: I know that I can use the OnDeserializing attribute to initialize my object when deserialization begins, this is not the subject of my question.

推荐答案

的DataContractSerializer (如的BinaryFormatter )没有按' T选用任何的构造。它创建的对象为空的内存。

DataContractSerializer (like BinaryFormatter) doesn't use any constructor. It creates the object as empty memory.

例如:

    Type type = typeof(Customer);
    object obj = System.Runtime.Serialization.
        FormatterServices.GetUninitializedObject(type);

的假设是,反序列化过程(或者根据需要回调)将充分初始化。

The assumption is that the deserialization process (or callbacks if necessary) will fully initialize it.

这篇关于DataContractSerializer的不叫我的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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