c# - 使用反射在 C# 中创建没有默认构造函数的类型实例

标签 c# reflection instantiation default-constructor

以下面的类为例:

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/

相关文章:

c# - 如何缩短这个通用列表?

c# - OperationContext 中的 header

c# - 你能在一个衬里中获得最大长度的 String.Split 吗?

c# - SharePoint 对象模型 : connect to remote server?

swift - 根据函数参数创建类的实例

java - 动态实例化嵌套在抽象类中的内部类

c# - 获取一系列对象中所有属性的默认值的通用解决方案

php - 使用反射通过引用传递参数

java - java中的不可变类

variable-assignment - 如何从 VHDL 中的内部架构写入两个输出端口?