vb.net - 如何指定 Enumerable.Count() 而不是 List.Count?

标签 vb.net extension-methods

尝试使用 Enumerable.Count() 时Visual Basic 的扩展方法,以下代码会导致编译时错误:

Imports System.Linq

Module Module1

    Sub Main()
        Dim l As New List(Of Foo) From {New Foo("a"), New Foo("b"), New Foo("a")}

        Dim i As Integer = l.Count(Function(foo) foo.Bar = "a")

        Console.WriteLine(i)
        Console.ReadLine()
    End Sub

    Class Foo

        Sub New(ByVal bar As String)
            Me.Bar = bar
        End Sub

        Public Property Bar As String
    End Class
End Module

产生的错误是:

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



我的目标是 .NET 4.0,所以应该支持扩展方法。还值得注意的是,C# 中的等效代码正确地推断出扩展方法......

考虑到我作为参数传递的谓词,为什么编译器无法推断 Enumerable.Count 的使用,以及如何使用扩展方法而不是 List 的 Count 属性?

最佳答案

VB.Net 编译器首先尝试查找 CountList实例,它会找到 Count属性(property)。使用此属性而不是扩展方法,因为字段和属性总是按名称隐藏扩展方法。我不知道这在 Visual Basic 语言规范中是在哪里说明的,但您可以在 MSDN Magazin article 中阅读更多内容。 :

Fields and properties always shadow extension methods by name. Figure 4 shows an extension method and public field with the same name and various calls. Though the extension method contains a second argument, the field shadows the extension method by name and all calls using this name result in accessing the field. The various overloaded calls will all compile, but their results at run time may be unexpected since they will bind to the property and use the default property behavior to return a single character or result in a runtime exception. It is important to choose the names of your extension methods so you avoid clashes with properties, fields, and existing instance methods.



所以,Count(Function(foo) foo.Bar = "a")可能意味着:调用Count -拥有 Function(foo) foo.Bar = "a" 的属性(property), 或取 Count 的结果-property 并使用 Function(foo) foo.Bar = "a" 对其进行索引,这可能是完全有效的,因为 VB.Net 中的索引属性可以采用任何参数。

这适用于 C#(我猜),因为 C# 编译器更容易区分方法调用和属性访问,因为与 VB.Net C# 不同的是,C# 不允许属性和索引属性上的任意参数。

要使用扩展方法,您可以像调用其他所有静态(共享)方法一样调用它:
Dim i As Integer = Enumerable.Count(l, Function(foo) foo.Bar = "a")

或调用CallIEnumerable明确:
Dim i As Integer = l.AsEnumerable().Count(Function(foo) foo.Bar = "a")

关于vb.net - 如何指定 Enumerable.Count() 而不是 List.Count?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15961308/

相关文章:

c# - VS 2005 工具箱类控件.NET

c# - 我可以使用方法代替带有额外参数的 Lambda 表达式吗

javascript - 从 AJAX 请求反序列化 Webmethod 中的 JSON

ios - 由于 'internal' 保护级别 swift 4,扩展初始化程序无法访问

asp.net - 为什么代码会被 ASP 触发一次 :ImageButton Click not Triggered

.net - 我的 VB.NET 解决方案不包含 Main 函数

.net - 在 VB 和 C# 中使用 Action/Func/Delegates/Lambda 编写扩展方法

c# - 运算符作为 C# 中的方法参数

C#:隐式运算符和扩展方法

asp.net-mvc-3 - 滚动我自己的@Html.BeginfOrm()