int[] arr = new int[5];
        Console.WriteLine(arr.Count.ToString());//Compiler Error
        Console.WriteLine(((ICollection)arr).Count.ToString());//works print 5
        Console.WriteLine(arr.Length.ToString());//print 5

你对此有解释吗?

有帮助吗?

解决方案

数组有.Length,而不是.Count。

但这在ICollection等上可用(作为显式接口实现)。

基本上,与:

相同
interface IFoo
{
    int Foo { get; }
}
class Bar : IFoo
{
    public int Value { get { return 12; } }
    int IFoo.Foo { get { return Value; } } // explicit interface implementation
}

Bar 没有公开的 Foo 属性 - 但是如果你转换为 IFoo ,它就可用了:

    Bar bar = new Bar();
    Console.WriteLine(bar.Value); // but no Foo
    IFoo foo = bar;
    Console.WriteLine(foo.Foo); // but no Value

其他提示

System.Array 实现 ICollection 接口时,它不直接公开 Count 属性。您可以在MSDN文档中看到 ICollection.Count 显式实现这里

这同样适用于 IList.Item

请查看此博客条目,了解有关显式和隐式接口实现的更多详细信息:隐式和显式接口实现

虽然这不能直接回答 的问题,但如果您使用的是.NET 3.5,则可以包含命名空间;

using System.Linq;

然后允许您使用Count()方法,类似于将int数组转换为ICollection时。

using System.Linq;

int[] arr = new int[5];
int int_count = arr.Count();

你也可以在Linq中使用一系列很好的功能:)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top