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
获取此对象的实例时,您将看到字段_wasConstructorCalled
为false
。
那么,WCF如何做到这一点呢?这是一种其他人也可以使用的技术,还是隐藏在我们面前?
发布于 2008-10-07 17:20:30
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
发布于 2010-04-03 01:41:24
是的,FormatterServices.GetUninitializedObject()是魔力的源泉。
如果你想做任何特殊的初始化,请看这里。http://blogs.msdn.com/drnick/archive/2007/11/19/serialization-and-types.aspx
https://stackoverflow.com/questions/178645
复制相似问题