我还没有注意到这种行为,也许是因为我更喜欢 VB.NET 中的查询语法并将查询和执行方法拆分为不同的语句。
如果我尝试编译以下简单查询:
Dim wordList As List(Of String) = New List(Of String)
Dim longWords As Int32 = wordList.Count(Function(word) word.Length > 100)
编译器不喜欢这样,因为他不希望有任何参数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)
为什么会这样?是什么阻止编译器使用Enumerable
扩展方法Count http://msdn.microsoft.com/en-us/library/vstudio/bb535181(v=vs.100).aspx而不是ICollection.Count http://msdn.microsoft.com/en-us/library/27b47ht3(v=vs.110).aspx财产。请注意,我已经添加了Imports System.Linq
以及两者Option Strict
and Option Infer
are On
。我正在使用.NET 4.0(Visual Studio 2010)。
我很困惑,因为在 C# 中这没有问题:
List<String> wordList = new List<String>();
int longWordCount = wordList.Count(word => word.Length > 100);
It's 按设计,引用自MSDN http://msdn.microsoft.com/en-us/library/bb384936.aspx:
对于属性,情况更简单:如果扩展方法与其扩展的类的属性同名,则扩展方法不可见且无法访问。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)