【问题标题】:Invoke method with optional arguments使用可选参数调用方法
【发布时间】:2013-10-11 20:05:45
【问题描述】:

我正在尝试使用一些可选参数根据其名称调用方法:

var methodInfo = this.GetType().GetMethod("Foo", 
                                BindingFlags.NonPublic | BindingFlags.Instance);

var queryString = _httpContext.Request.QueryString;
var somethingElse = new List<int>(){ 1,2,3 };
var args = new object[]{ queryString, somethingElse  };

if(methodInfo != null)
    methodInfo.Invoke(this, args);


private void Foo(object[] args)
{
    foreach(var item in args)
       //...
}

如果我只将queryString 传递给args,我会收到以下错误:

“System.Web.HttpValueCollection”类型的对象无法转换为“System.Object[]”类型。

methodInfo.Invoke() 中的 object[] parameters 参数打算如何使用?

【问题讨论】:

  • if(methodInfo == null) methodInfo.Invoke(this, args); 此代码将永远无法工作...
  • 哪一行抛出了这个错误?
  • @Knaģis !=,抱歉写在我头上
  • 我发现它在计算参数之前尝试“调用”该方法非常有趣,我不知道:) 我以为你会得到类似WrongNumberOfArgumentException 的东西。 (正如@Knaģis 和@Alessandro 都指出的那样,您误解了如何将多个参数传递给调用方法。)

标签: c# asp.net


【解决方案1】:

尝试:

methodInfo.Invoke(this, new object[] { args });

参数只有1,是一个对象数组。如果你传递args 它考虑多个参数。

【讨论】:

    【解决方案2】:

    由于您的方法采用object[] 类型的单个参数,您需要将该参数作为另一个数组中的数组传递。

    // this is what is passed to your method as the first parameter
    var args = new object[]{ queryString, somethingElse  };
    
    // the .Invoke method expects an array of parameters...
    methodInfo.Invoke(this, new object[] { args });
    

    如果您的方法是 void Foo(string a, List&lt;int&gt; b) 等,那么 Invoke 会像这样调用

    // the .Invoke method expects an array of parameters...
    methodInfo.Invoke(this, new object[] { queryString, somethingElse });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 2017-09-02
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      相关资源
      最近更新 更多