DataContractSerializer 不调用我的构造函数? [英] DataContractSerializer doesn't call my constructor?
问题描述
我刚刚意识到一些疯狂的事情,我认为这是完全不可能的:反序列化对象时,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
)不使用 any 构造函数.它将对象创建为空内存.
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屋!