.net - 为什么 List(Of T) 没有 Count()?

标签 .net vb.net linq extension-methods

Public Class MyList
    Inherits List(Of MyObject)

    Public ReadOnly Property SelectedCount() As Integer
        Get
            Return Me.Count(Function(obj) obj.IsSelected)
        End Get
    End Property
End Class

上面的代码会导致编译时错误。如您所见,我正在尝试使用扩展方法 Count(<predicate>) .我猜这个错误是因为在 List 中有一个类似命名的属性 Count类本身也是如此,隐藏了扩展成员。

我的问题是:
  • 我是否需要将我的类显式转换为其他内容才能访问 Count扩展方法?如果是这样,在上面的场景中到底应该是哪个类?
  • 为什么编译器不能从用法推断出我指的是方法而不是属性?
  • 考虑到这是一种大量使用的方法(有时可能每秒调用数百次),转换是否涉及大量开销?
  • 在这方面,C# 是否比 VB.NET 更好?

  • 如果有事的话,我将 .NET 4.0 与 VS2010 一起使用。

    编辑

    错误信息:

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

    最佳答案

    调用没有扩展方法语法的方法:

    Public Class MyList
        Inherits List(Of MyObject)
    
        Public ReadOnly Property SelectedCount() As Integer
            Get
                Return Enumerable.Count(Me, Function(obj) obj.IsSelected)
            End Get
        End Property
    End Class
    

    确保您已向 System.Linq 添加了导入。

    关于.net - 为什么 List(Of T) 没有 Count()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18743457/

    相关文章:

    c# 方法类型推断的麻烦

    .net - 来自 .Net 的 Windows 菜单

    asp.net - 将 ID 值传递给后面代码中的 OnCheckedChange 事件

    .net - GroupBy 中的内存节省

    .net - 我们如何在 aspx 页面的用户控件上使用必填字段验证器

    c# - tasks 参数包含一个空值

    c# - 使用 .net 组合框

    c# - 如何获取整个强类型DataRow的原始值?

    c# - 两个列表 - 获取公共(public)字段?

    c# - 我应该使用 ToList() 深度克隆 IList 吗?