一尘不染

WCF反序列化如何在不调用构造函数的情况下实例化对象?

c#

WCF反序列化正在进行中。如何在不调用其构造函数的情况下实例化数据协定类型的实例?

例如,考虑以下数据合同:

[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

那么,WCF如何做到这一点?这是其他人也可以使用的技术,还是对我们隐藏?


阅读 218

收藏
2020-05-19

共1个答案

一尘不染

FormatterServices.GetUninitializedObject()将创建实例而不调用构造函数。我通过使用Reflector并深入研究了一些核心.Net序列化类来找到此类。

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

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

2020-05-19