更新时间:2023-01-17 12:53:05
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