【问题标题】:How can I invoke a method that has params string[] as its only parameter without send values如何调用以 params string[] 作为唯一参数而不发送值的方法
【发布时间】:2017-05-24 22:33:16
【问题描述】:

我想调用这个方法:

public IEnumerable<TEntity> SelectAll(params string[] entitiesToLoad)

但在大多数情况下,我不会加载关系实体,所以我想在不发送entitiesToLoad 值的情况下调用它,如下所示:

var dbResult = methodInfo.Invoke(repository, null);

但是会抛出异常,因为参数个数不相等。

有没有办法在不将参数 string[] 更改为另一种类型的参数的情况下执行此操作?

我试过string entitiesToLoad = null as parameter,我得到了同样的错误。

【问题讨论】:

  • 传递空字符串数组
  • 你为什么不直接通过new string[0]
  • new string[0] 抛出同样的错误

标签: c# system.reflection


【解决方案1】:

传递一个空数组,因为这是 C# 编译器在指示可变参数方法没有参数时将传递的内容:

var dbResult = methodInfo.Invoke(repository, new object[] { new string[0] });

请注意,您必须将字符串数组包装到对象数组中,因为该对象数组表示参数列表。第一个传递的参数是空字符串数组。

【讨论】:

  • @RaphaelRibeiro:我认为您必须将空字符串数组包装到对象数组中。我已经相应地更新了答案。
  • 我会把它标记为答案,它很丑但是......谢谢。
【解决方案2】:

这似乎是使用方法重载的完美场景。如果您不需要该值,为什么要发送它?:

public IEnumerable<TEntity> SelectAll(params string[] entitiesToLoad)
{
     //...
}

public IEnumerable<TEntity> SelectAll()
{
     //...
}

【讨论】:

  • 我想用作可选
  • 如果你不需要它就不要发送它会更干净。但是如果你坚持这样做,你可以设置为可选,它应该像我测试过的那样工作 public IEnumerable SelectAll(string[] entityToLoad = null)
  • 你能显示你调用该方法的那一行吗,我在这里遇到了同样的错误。
  • 这样你就可以这样称呼它:SelectAll();
  • 对不起,您不明白,我正在使用 MethodInfo.Invoke 通过反射调用该方法。你所做的方式有效,但我处于一般场景中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-03
  • 2019-06-05
相关资源
最近更新 更多