实例化一个带参数的构造函数与反思的内部类 [英] Instantiating a constructor with parameters in an internal class with reflection
本文介绍了实例化一个带参数的构造函数与反思的内部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我沿着这个线的东西:
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(类型,对象[])
不考虑非公开构造函数。
The issue is that Activator.CreateInstance(Type, object[])
does not consider non-public constructors.
例外
MissingMethodException:没有匹配
公共构造被发现。
MissingMethodException: No matching public constructor was found.
这是很容易通过改变构造函数公共
的知名度显示;在code,那么正常工作。
This is easily shown by changing the constructor to public
visibility; 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);
这篇关于实例化一个带参数的构造函数与反思的内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文