使用反射在 C# 中创建没有默认构造函数的类型实例 [英] Creating instance of type without default constructor in C# using reflection

查看:24
本文介绍了使用反射在 C# 中创建没有默认构造函数的类型实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下面的类为例:

class Sometype
{
    int someValue;

    public Sometype(int someValue)
    {
        this.someValue = someValue;
    }
}

然后我想使用反射创建这种类型的实例:

I then want to create an instance of this type using reflection:

Type t = typeof(Sometype);
object o = Activator.CreateInstance(t);

通常这会起作用,但是因为 SomeType 没有定义无参数构造函数,对 Activator.CreateInstance 的调用将抛出 MissingMethodException 并显示消息没有为此对象定义无参数构造函数." 是否还有另一种方法来创建这种类型的实例?将无参数构造函数添加到我所有的类中会有点糟糕.

Normally this will work, however because SomeType has not defined a parameterless constructor, the call to Activator.CreateInstance will throw an exception of type MissingMethodException with the message "No parameterless constructor defined for this object." Is there an alternative way to still create an instance of this type? It'd be kinda sucky to add parameterless constructors to all my classes.

推荐答案

我最初发布了这个答案 这里,但这里是重印,因为这不是完全相同的问题,但有相同的答案:

I originally posted this answer here, but here is a reprint since this isn't the exact same question but has the same answer:

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.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# 中创建没有默认构造函数的类型实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆