gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:13:23 25 4
gpt4 key购买 nike

我还没有注意到这种行为,可能是因为我更喜欢 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" has no parameters and its return type cannot be indexed.

如果我将它声明为 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而不是 ICollection.Count属性(property)。请注意,我添加了 Imports System.Linq 并且 Option StrictOption Infer 都是 On。我正在使用 .NET 4.0 (Visual Studio 2010)。

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

List<String> wordList  = new List<String>();
int longWordCount = wordList.Count(word => word.Length > 100);

最佳答案

这是设计,引自MSDN :

The situation is simpler with properties: if an extension method has the same name as a property of the class it extends, the extension method is not visible and cannot be accessed.

关于c# - 不能将 Enumerable.Count 与 List 一起使用,编译器假定 List.Count,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26235134/

25 4 0