不能使用Enumerable.Count与列表,编译器假定List.Count [英] Cannot use Enumerable.Count with List, compiler assumes List.Count

查看:225
本文介绍了不能使用Enumerable.Count与列表,编译器假定List.Count的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还没有发现这种行为还没有,也许是因为我preFER查询语法在VB.NET和分裂的查询和执行,方法为不同的语句。

如果我尝试编译下面这个简单的查询:

 昏暗的词库方式列表(字符串)=新名单(串)
昏暗的长字作为的Int32 = wordList.Count(功能(字)word.Length→100)
 

编译器不喜欢这一点,因为他预计没有论据 List.Count

  

公共只读属性算作整数没有任何参数和返回值类型不能被索引。

如果我宣布它作为的IEnumerable(串)它按预期工作:

 昏暗wordSeq为IEnumerable(串)=新名单(串)
昏暗的长字作为的Int32 = wordSeq.Co​​unt(功能(字)word.Length→100)
 

为什么会这样呢?什么$ P $使用该可枚举扩展方法<一pvents编译器href="http://msdn.microsoft.com/en-us/library/vstudio/bb535181(v=vs.100).aspx"><$c$c>Count代替<一个href="http://msdn.microsoft.com/en-us/library/27b47ht3(v=vs.110).aspx"><$c$c>ICollection.Count属性。请注意,我已经添加了进口System.Linq的无一不选项严格选项推断。我using.NET 4.0(Visual Studio 2010中)。

我很困惑,因为在C#这工作不会有问题:

 名单,其中,字符串&GT;单词表=新的名单,其中,字符串&GT;();
INT longWordCount = wordList.Count(字=&GT; word.Length→100);
 

解决方案

这是按设计,引述的MSDN

  

的情况更简单与属性:如果一个扩展方法具有相同的名称,因为它扩展了类的属性,扩展方法是不可见的,并且不能被访问

I haven't noticed this behaviour yet, maybe because i prefer query syntax in VB.NET and split the query and the execution-methods into different statements.

If i try to compile following simple query:

Dim wordList As List(Of String) = New List(Of String)
Dim longWords As Int32 = wordList.Count(Function(word) word.Length > 100)

The compiler doesn't like this because he expects no arguments for List.Count:

"Public Readonly Property Count As Integer" has no parameters and its return type cannot be indexed.

If i declare it as IEnumerable(Of String) it works as expected:

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

Why is that so? What prevents the compiler from using the Enumerable extension method Count instead of the ICollection.Count property. Note that i've added Imports System.Linq and both Option Strict and Option Infer are On. I'm using.NET 4.0 (Visual Studio 2010).

I'm confused because in C# this works without a problem:

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

解决方案

It's by design, quote from 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.

这篇关于不能使用Enumerable.Count与列表,编译器假定List.Count的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆