以下面的类为例:
class Sometype
{
int someValue;
public Sometype(int someValue)
{
this.someValue = someValue;
}
}
然后我想使用反射创建这种类型的实例:
Type t = typeof(Sometype);
object o = Activator.CreateInstance(t);
通常这会起作用,但是因为 SomeType
尚未定义无参数构造函数,对 Activator.CreateInstance
的调用将抛出 MissingMethodException
类型的异常带有消息“没有为此对象定义无参数构造函数。”是否还有另一种方法来创建这种类型的实例?向我的所有类添加无参数构造函数有点糟糕。
最佳答案
我最初发布了这个答案 here ,但这里是转载,因为这不是完全相同的问题,但具有相同的答案:
FormatterServices.GetUninitializedObject()
将在不调用构造函数的情况下创建一个实例。我通过使用 Reflector 找到了这个类并挖掘一些核心 .Net 序列化类。
我使用下面的示例代码对其进行了测试,看起来效果很好:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Runtime.Serialization;
namespace NoConstructorThingy
{
class Program
{
static void Main(string[] args)
{
MyClass myClass = (MyClass)FormatterServices.GetUninitializedObject(typeof(MyClass)); //does not call ctor
myClass.One = 1;
Console.WriteLine(myClass.One); //write "1"
Console.ReadKey();
}
}
public class MyClass
{
public MyClass()
{
Console.WriteLine("MyClass ctor called.");
}
public int One
{
get;
set;
}
}
}
关于c# - 使用反射在 C# 中创建没有默认构造函数的类型实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/390578/