使用方法组替换Lambda表达式时编译器错误

Seb*_*ler 4 .net linq linq-to-objects

我喜欢Linq语法及其强大功能,但有时候我无法理解为什么事情会起作用.

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

Regex regex = new Regex( ... );

int result1 = stringList.Count(regex.IsMatch);
IEnumerable<string> result2 = stringList.Where (x => regex.IsMatch (x));
Run Code Online (Sandbox Code Playgroud)

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

作为Count和Where两者采用相同的类型参数

Func<string, bool>
Run Code Online (Sandbox Code Playgroud)

我无法理解为什么在执行此操作时出现编译器错误:

IEnumerable<string> result2 = stringList.Where (regex.IsMatch);
Run Code Online (Sandbox Code Playgroud)

Ani*_*Ani 5

从本质上讲,这是一个重载解决问题.

Count只有一个带有两个参数的重载(扩展参数+谓词),但Where有两个(一个谓词考虑项目索引,另一个不考虑项目索引).更复杂的是,Regex.IsMatch它有自己的多重载荷.现在事实证明,编译器是正确的,因为抱怨歧义2的这些重载的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>)
Run Code Online (Sandbox Code Playgroud)

...但是可能存在涉及方法组的其他相关案例(当需要返回类型分析时),即使对于人类没有歧义,编译器也可以抱怨模糊性.