[英]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”的构造函数..
有任何想法吗?
问题是Activator.CreateInstance(Type, object[])
不考虑非公共构造函数。
例外
MissingMethodException:找不到匹配的公共构造函数。
通过将构造函数更改为public
可见性可以很容易地显示出来; 然后代码正常工作。
这是一个解决方法(已测试):
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);
如果您只需要无参数构造函数,那么它也可以工作:
//using the overload: public static object CreateInstance(Type type, bool nonPublic)
object instantiatedType = Activator.CreateInstance(typeToInstantiate, true)
(测试成功)
object instantiatedType =
Activator.CreateInstance(typeToInstantiate,
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance,
null, new object[] {parameter}, null);
这有两个问题:
new object[] {parameter}
帮助它处理传递object[]
作为方法的单个参数的问题,该方法接受params object[]
参数 BindingFlags
有助于解析非公共构造函数 (这两个null
与绑定器有关 ;默认绑定器行为适用于我们想要的)
您需要调用Activator.CreateInstance
的不同重载,以允许您传递nonPublic
或BindingFlags
参数。
我发现所有这些CreateInstance
重载都很笨拙; 我更喜欢做的是:
typeToInstantiate.GetConstructor()
,传递BindingFlags.NonPublic
ConstructorInfo.Invoke
,向其传递构造函数参数 改为
Activator.CreateInstance(typeToInstantiate,new object[] { parameter });
这是因为您的构造函数还期望对象数组和激活器已将其拆分为单独的对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.