【问题标题】:Compiler error when replacing Lambda expression with method group用方法组替换 Lambda 表达式时出现编译器错误
【发布时间】:2011-12-02 01:25:19
【问题描述】:

我喜欢 Linq 语法和它的强大功能,但有时我就是不明白为什么事情是这样工作的。

就像现在一样。我有以下代码:

Regex regex = new Regex( ... );

int result1 = stringList.Count(regex.IsMatch);
IEnumerable<string> result2 = stringList.Where (x => regex.IsMatch (x));

正如您在第一个查询中看到的,我可以使用较短的方法组“regex.IsMatch”,但在第二个查询中我必须编写“x => regex.IsMatch (x)”。

As Count 和 Where 都采用相同类型的参数

Func<string, bool>

执行此操作时,我不明白为什么会出现编译器错误:

IEnumerable<string> result2 = stringList.Where (regex.IsMatch);

【问题讨论】:

    标签: .net linq linq-to-objects


    【解决方案1】:

    本质上,这是一个重载解决问题。

    Count 只有一个重载需要两个参数(扩展参数 + 谓词),但 Where 有两个(一个是谓词考虑项目索引,一个不考虑)。更复杂的是,Regex.IsMatch 有自己的多个重载。 现在证明编译器抱怨歧义是正确的,因为IsMatch 的这些重载中有两个 是真正适用的(每个都与Where 的不同重载兼容):

    // Where overload without item-index
    Regex.IsMatch(string) is compatible with Where<string>(string, Func<string, bool>)
    
    // Where overload with item-index
    Regex.IsMatch(string, int) is compatible with Where<string>(string, Func<string, int, bool>)
    

    ...但可能还有其他涉及方法组的相关案例(当需要返回类型分析时)compiler can complain about ambiguity even when there is no ambiguity for a human

    【讨论】:

    • 谢谢,现在说得通了 :)
    猜你喜欢
    • 2011-07-15
    • 2013-04-07
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多