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

查看:1560
本文介绍了使用反射在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.

推荐答案

我最初发布这个答案<一个href=\"http://stackoverflow.com/questions/178645/how-does-wcf-deserialization-instantiate-objects-without-calling-a-constructor#179486\">here,但这里是一个翻版,因为这是不完全一样的问题,但有相同的答案:

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()将不调用构造函数创建一个实例。我用反射并通过一些核心净系列化类挖掘发现了这个类。

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.

我测试了它使用下面的示例code,它看起来像它的伟大工程:

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天全站免登陆