【问题标题】:Errors when trying to add ref to an overloaded method's parameter [duplicate]尝试将 ref 添加到重载方法的参数时出错 [重复]
【发布时间】:2012-08-29 19:42:58
【问题描述】:

当我尝试将ref 添加到重载方法的参数时,为什么会出现以下错误?

最好的重载方法匹配 'WindowsFormsApplication1.Form1.SearchProducts(int)' 有一些无效 论据

参数 1:无法从 'ref 转换 System.Collections.Generic.List' 到 'int'

这是一些(简化的)代码:

public virtual IList<int> SearchProducts(int categoryId)
{
    List<int> categoryIds = new List<int>();
    if (categoryId > 0)
        categoryIds.Add(categoryId);
    return SearchProducts(ref categoryIds);
}

public virtual IList<int> SearchProducts(ref IList<int> categoryIds)
{
    return new List<int>();
}

编辑:

你们中的一些人问我为什么在这种情况下我需要ref,答案是我可能不需要它,因为我可以清除列表并添加新元素(我不需要创建新的参考)。但问题不在于我需要或不需要ref,而在于我为什么会出错。而且由于我没有找到答案(在谷歌搜索了一会儿之后),我认为这个问题很有趣,值得在这里提问。看来你们中的一些人不认为这是一个好问题并投票关闭它......

【问题讨论】:

  • 你想做什么?不清楚为什么在这种情况下需要使用ref
  • @ClaudioRedi:OP 明确表示代码已被简化。他如何使用ref 与主题无关。
  • @Ed S.:既然我在这里,只是想看看他是否误解了ref 会做什么。在我看来,他在滥用它,所以我可以首先解决他删除 ref 的问题 :)
  • @ClaudioRedi:当然,这是一个很好的评论(我也这么认为),但他说它已经被简化了,所以我想我会不管它。也就是说......我也不需要对你发表评论:D
  • @ClaudioRedi 我可能不需要ref,但这不是问题所在(见编辑)。

标签: c#


【解决方案1】:

当您通过引用传递参数时,编译时类型必须是精确与参数类型相同的类型。

假设第二种方法写成:

public virtual IList<int> SearchProducts(ref IList<int> categoryIds)
{
    categoryIds = new int[10];
    return null;
}

这必须编译,因为int[] 实现了IList&lt;int&gt;。但是,如果调用者实际上有一个 List&lt;int&gt; 类型的变量,它现在有一个对 int[] 的引用,则会破坏类型安全...

您可以通过在调用方法 IList&lt;int&gt; 而不是 List&lt;int&gt; 中声明类型为 categoryIds 来解决此问题 - 但我强烈怀疑您实际上并不想传递参数首先通过参考。需要这样做的情况相对较少。您对C# parameter passing 感觉如何?

【讨论】:

  • @EdS.:有一个惊喜 :) 我现在也投票结束了,但我会留下这个答案,以防它有助于 OP 看到它在他的上下文中应用。跨度>
  • 是的,我实际上删除了评论并投了赞成票,因为它更简单且互补
  • 我投了赞成票,但随后阅读了 Ed S. 的回复和 darnit Skeet,你已经有足够的积分了! :P 并不是说​​与 Eric Lippert 分享特别是在传播财富.. 呵呵
  • @JonSkeet 您怀疑是对的,所以感谢您指出我don't actually want to pass the argument by reference in the first place。 (见编辑)
【解决方案2】:

尝试以下方法:

public virtual IList<int> SearchProducts(int categoryId)
{
    IList<int> categoryIds = new List<int>();
    if (categoryId > 0)
    categoryIds.Add(categoryId);
    return SearchProducts(ref categoryIds);
}

【讨论】:

    【解决方案3】:

    您需要向该方法传递一个可分配的 IList(of int)。

    IList<int> categoryIds = new List<int>();
    

    【讨论】:

      猜你喜欢
      • 2018-08-12
      • 2018-05-25
      • 1970-01-01
      • 2014-04-21
      • 1970-01-01
      • 2016-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多