将字符串数组参数传递给 Invoke 方法
我有这个类:
using System.Linq;
namespace TestNamespace {
public class Program {
public static void Main(string[] args) {
//does stuff
}
}
}
我正在加载上面的程序集,并希望使用字符串数组参数调用该方法。
这给了我一个空例外:
private static object[] parameters = new object[1];
string[] pa = { "1", "2" };
parameters[0] = pa;
//Creating target and other code
bool retVal = (bool)target.Invoke(null, parameters);
有什么想法吗?谢谢
I have this class:
using System.Linq;
namespace TestNamespace {
public class Program {
public static void Main(string[] args) {
//does stuff
}
}
}
I am loading the above assembly and want to invoke the method with a string array parameter.
This gives me a null exception:
private static object[] parameters = new object[1];
string[] pa = { "1", "2" };
parameters[0] = pa;
//Creating target and other code
bool retVal = (bool)target.Invoke(null, parameters);
Any thoughts? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
NullReferenceException
在哪里。您确定正确反映了MethodInfo
并且target
不是null
吗?这就是我对这里到底发生了什么的怀疑。如果方法中抛出NullReferenceException
,它将被包装在TargetInitationException
中,因此我怀疑NullReferenceException
是因为目标
为空。需要明确的是,加载和调用该方法的方式如下:
MethodInfo.Invoke
的parameters
参数是一个具有相同编号的object[]
、被调用方法的参数的顺序和类型。在您的例子中,您有一个string[]
类型的参数。因此,MethodInfo.Invoke
的object[]
参数应该是一个包含一个元素的数组,并且该元素是string[]
的实例。这就是我用上面的语法所完成的。Where's the
NullReferenceException
. Are you sure that you're reflecting theMethodInfo
correctly and thattarget
is notnull
? That's my suspicion as to what's really going on here. If there were aNullReferenceException
being thrown in the method, it would be wrapped in aTargetInvocationException
and thus I suspect theNullReferenceException
is becausetarget
is null.To be clear, here's how you load and invoke the method:
The
parameters
parameter toMethodInfo.Invoke
is anobject[]
with the same number, order and types of the parameters for the method being invoked. In your case, you have a single parameter of typestring[]
. Thus, theobject[]
parameter toMethodInfo.Invoke
should be an array with one element, and that element is an instance ofstring[]
. That is what I have accomplished with the syntax above.