[英]How to pass object[] to Activator.CreateInstance(type, params object[])
I have a class which contains an empty constructor and one that accepts an array of objects as its only parameter. 我有一个包含空构造函数的类,并且它接受一个对象数组作为唯一参数。 Something like...
就像是...
public myClass(){ return; }
public myClass(object[] aObj){ return; }
This is the CreateInstance() method call that I use 这是我使用的CreateInstance()方法调用
object[] objectArray = new object[5];
// Populate objectArray variable
Activator.CreateInstance(typeof(myClass), objectArray);
it throws System.MissingMethodException
with an added message that reads "Constructor on type 'myClass' not found" 它抛出
System.MissingMethodException
并添加一条消息,显示“未找到类型'myClass'上的构造函数”
The bit of research that I have done has always shown the method as being called 我所做的一些研究总是将方法显示为被调用
Activator.CreateInstance(typeof(myClass), arg1, arg2);
Where arg1 and arg2 are types (string, int, bool) and not generic objects. 其中arg1和arg2是类型(string,int,bool)而不是通用对象。 How would I call this method with only the array of objects as its parameter list?
如何仅使用对象数组作为参数列表来调用此方法?
Note: I have tried adding another variable to the method signature. 注意:我尝试在方法签名中添加另一个变量。 Something like...
就像是...
public myClass(object[] aObj, bool notUsed){ return; }
and with this the code executed fine. 并且这个代码执行得很好。 I have also seen methods using reflection which were appropriate but I am particularly interested in this specific case.
我也看过使用反射的方法,但我对这个具体案例特别感兴趣。 Why is this exception raised if the method signature does in fact match the passed parameters?
如果方法签名实际上与传递的参数匹配,为什么会引发此异常?
把它投射到object
:
Activator.CreateInstance(yourType, (object) yourArray);
Let's say you have constructor: 假设你有构造函数:
class YourType {
public YourType(int[] numbers) {
...
}
}
I believe you would activate like so by nesting your array, the intended parameter, as a item of the params array: 我相信你会通过将你的数组(预期参数)嵌套为params数组的项来激活:
int[] yourArray = new int[] { 1, 2, 4 };
Activator.CreateInstance(typeof(YourType ), new object[] { yourArray });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.