将字符串数组参数传递给 Invoke 方法

发布于 2024-12-14 23:58:16 字数 507 浏览 1 评论 0原文

我有这个类:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

紫竹語嫣☆ 2024-12-21 23:58:16

NullReferenceException 在哪里。您确定正确反映了 MethodInfo 并且 target 不是 null 吗?这就是我对这里到底发生了什么的怀疑。如果方法中抛出 NullReferenceException ,它将被包装在 TargetInitationException 中,因此我怀疑 NullReferenceException 是因为 目标 为空。

需要明确的是,加载和调用该方法的方式如下:

var target = typeof(Program)
                 .GetMethod("Main", BindingFlags.Public | BindingFlags.Static);
bool retVal = (bool)target.Invoke(null, new object[] { pa });

MethodInfo.Invokeparameters 参数是一个具有相同编号的 object[] 、被调用方法的参数的顺序和类型。在您的例子中,您有一个 string[] 类型的参数。因此,MethodInfo.Invokeobject[] 参数应该是一个包含一个元素的数组,并且该元素是 string[] 的实例。这就是我用上面的语法所完成的。

Where's the NullReferenceException. Are you sure that you're reflecting the MethodInfo correctly and that target is not null? That's my suspicion as to what's really going on here. If there were a NullReferenceException being thrown in the method, it would be wrapped in a TargetInvocationException and thus I suspect the NullReferenceException is because target is null.

To be clear, here's how you load and invoke the method:

var target = typeof(Program)
                 .GetMethod("Main", BindingFlags.Public | BindingFlags.Static);
bool retVal = (bool)target.Invoke(null, new object[] { pa });

The parameters parameter to MethodInfo.Invoke is an object[] with the same number, order and types of the parameters for the method being invoked. In your case, you have a single parameter of type string[]. Thus, the object[] parameter to MethodInfo.Invoke should be an array with one element, and that element is an instance of string[]. That is what I have accomplished with the syntax above.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文