如何WCF反序列化实例化对象没有调用构造函数? [英] How does WCF deserialization instantiate objects without calling a constructor?
问题描述
有一些神奇与WCF反序列化回事。它是如何实例化数据契约类型的实例,而无需调用构造函数?
There is some magic going on with WCF deserialization. How does it instantiate an instance of the data contract type without calling its constructor?
例如,考虑这个数据契约:
For example, consider this data contract:
[DataContract]
public sealed class CreateMe
{
[DataMember] private readonly string _name;
[DataMember] private readonly int _age;
private readonly bool _wasConstructorCalled;
public CreateMe()
{
_wasConstructorCalled = true;
}
// ... other members here
}
在通过的DataContractSerializer
获取该对象的实例,你会看到领域 _wasConstructorCalled
是假
。
When obtaining an instance of this object via DataContractSerializer
you will see that the field _wasConstructorCalled
is false
.
那么,如何WCF做到这一点?这是其他人可以使用过,或者是看不到它离我们的技术?
So, how does WCF do this? Is this a technique that others can use too, or is it hidden away from us?
推荐答案
FormatterServices.GetUninitializedObject()
将创建一个实例,而无需调用构造函数。我用反射并通过一些核心净序列化类的挖掘发现了这个类。
FormatterServices.GetUninitializedObject()
will create an instance without calling a constructor. I found this class by using Reflector and digging through some of the core .Net serialization classes.
我测试了它使用下面的示例code,它看起来像它的伟大工程:
I tested it using the sample code below and it looks like it works great:
using System;
using System.Reflection;
using System.Runtime.Serialization;
namespace NoConstructorThingy
{
class Program
{
static void Main()
{
// does not call ctor
var myClass = (MyClass)FormatterServices.GetUninitializedObject(typeof(MyClass));
Console.WriteLine(myClass.One); // writes "0", constructor not called
Console.WriteLine(myClass.Two); // writes "0", field initializer not called
}
}
public class MyClass
{
public MyClass()
{
Console.WriteLine("MyClass ctor called.");
One = 1;
}
public int One { get; private set; }
public readonly int Two = 2;
}
}
这篇关于如何WCF反序列化实例化对象没有调用构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!