为什么列表(Of T)中不具有计数()? [英] Why List(Of T) doesn't have Count()?

查看:202
本文介绍了为什么列表(Of T)中不具有计数()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 公共类MYLIST
    继承名单(作者为MyObject)

    公共只读属性SelectedCount()作为整数
        得到
            返回Me.Count(函数(OBJ)obj.IsSelected)
        最终获取
    高端物业
末级
 

以上code会导致编译时错误。正如你所看到的,我试图使用扩展方法计数(小于predicate>)。我猜的错误是因为有一个类似命名的属性Count在列表类本身也隐藏扩展名成员。

在这里我的问题是:

  1. 我是否需要显式转换我的课到别的访问计数扩展方法?如果是这样,到底是哪类应该是在上面的场景?

  2. 为什么不能从使用情况我指的是一个方法,而不是一个属性编译器推断?

  3. 请问铸造涉及显著开销,考虑到这是一个频繁使用的方​​法(可能有时被称为几百次,第二次)?

  4. 在这方面C#比任何VB.NET好?

我使用.NET 4.0与VS2010如果有事情做。

修改

错误消息:

  

公共只读属性算作整数'没有参数及其   返回类型不能被索引。

解决方案

调用在扩展方法的语法:

 公共类MYLIST
    继承名单(作者为MyObject)

    公共只读属性SelectedCount()作为整数
        得到
            返回Enumerable.Count(Me中,函数(OBJ)obj.IsSelected)
        最终获取
    高端物业
末级
 

请确保您所添加的导入System.Linq的。

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

The above code causes a compile-time error. As you can see, I'm trying to use extension method Count(<predicate>). I guess the error is because there is a similarly-named property Count in List class itself too, hiding the extension member.

My questions here are:

  1. Do I need to explicitly cast my class to something else to access Count extension method? If so, exactly which class should it be in the above scenario?

  2. Why can't the compiler infer from the usage that I'm referring to a method and not a property?

  3. Does casting involve significant overhead considering that this is a heavily used method (may at times be called hundreds of times a second)?

  4. Is C# any better than VB.NET in this regard?

I'm using .NET 4.0 with VS2010 if that has something to do.

EDIT

Error message:

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

解决方案

Call the method without the extension method syntax:

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

Make sure you have added an import to System.Linq.

这篇关于为什么列表(Of T)中不具有计数()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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