WCF反序列化如何在不调用构造函数的情况下实例化对象? [英] How does WCF deserialization instantiate objects without calling a constructor?

查看:31
本文介绍了WCF反序列化如何在不调用构造函数的情况下实例化对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 获取该对象的实例时,您将看到字段 _wasConstructorCalledfalse.

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() 将创建一个实例而不调用构造函数.我通过使用 Reflector 并挖掘一些核心找到了这个类.网络序列化类.

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.

我使用下面的示例代码对其进行了测试,看起来效果很好:

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;
    }
}

http://d3j5vwomefv46c.cloudfront.net/photos/large/687556261.png

这篇关于WCF反序列化如何在不调用构造函数的情况下实例化对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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