gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:30:50 25 4
gpt4 key购买 nike

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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com