不能将Enumerable.Count与List一起使用,编译器假定为List.Count

Tim*_*ter 7 .net c# linq vb.net

我还没有注意到这种行为,也许是因为我更喜欢VB.NET中的查询语法,并将查询和执行方法分成不同的语句.

如果我尝试编译以下简单查询:

Dim wordList As List(Of String) = New List(Of String)
Dim longWords As Int32 = wordList.Count(Function(word) word.Length > 100)
Run Code Online (Sandbox Code Playgroud)

编译器不喜欢这个,因为他希望没有参数List.Count:

"Public Readonly Property Count As Integer"没有参数,其返回类型无法编入索引.

如果我声明它IEnumerable(Of String)按预期工作:

Dim wordSeq As IEnumerable(Of String) = New List(Of String)
Dim longWords As Int32 = wordSeq.Count(Function(word) word.Length > 100)
Run Code Online (Sandbox Code Playgroud)

为什么会这样?什么阻止编译器使用Enumerable扩展方法Count而不是ICollection.Count属性.请注意,我已经添加了Imports System.Linq和这两个Option Strict和Option Infer的On.我正在使用.NET 4.0(Visual Studio 2010).

我很困惑,因为在C#中这没有问题:

List<String> wordList  = new List<String>();
int longWordCount = wordList.Count(word => word.Length > 100);
Run Code Online (Sandbox Code Playgroud)

Adr*_*tti 6

这是设计,引自MSDN:

具有属性的情况更简单:如果扩展方法与其扩展的类的属性具有相同的名称,则扩展方法不可见且无法访问.