使用反射在内部类中使用参数实例化构造函数 [英] Instantiating a constructor with parameters in an internal class with reflection

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

问题描述

我有一些类似的东西:

object[] parameter = new object[1];
parameter[0] = x;
object instantiatedType =
Activator.CreateInstance(typeToInstantiate, parameter);

internal class xxx : ICompare<Type>
{
    private object[] x;

    # region Constructors

    internal xxx(object[] x)
    {
        this.x = x;
    }

    internal xxx()
    {
    }

    ...
}

我得到:

抛出异常:System.MissingMethodException:未找到类型xxxx.xxx"的构造函数..

threw exception: System.MissingMethodException: Constructor on type 'xxxx.xxx' not found..

有什么想法吗?

推荐答案

问题在于 Activator.CreateInstance(Type, object[]) 不考虑非公共构造函数.

The issue is that Activator.CreateInstance(Type, object[]) does not consider non-public constructors.

例外

MissingMethodException: 不匹配找到公共构造函数.

MissingMethodException: No matching public constructor was found.

这很容易通过将构造函数更改为publicvisibility 来显示;然后代码可以正常工作.

This is easily shown by changing the constructor to publicvisibility; the code then works correctly.

这是一种解决方法(已测试):

Here's one workaround (tested):

 BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance;
 CultureInfo culture = null; // use InvariantCulture or other if you prefer
 object instantiatedType =   
   Activator.CreateInstance(typeToInstantiate, flags, null, parameter, culture);

如果您只需要无参数构造函数,这也可以:

If you only require the parameterless constructor this will work as well:

//using the overload: public static object CreateInstance(Type type, bool nonPublic)
object instantiatedType = Activator.CreateInstance(typeToInstantiate, true)

这篇关于使用反射在内部类中使用参数实例化构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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