我无法访问数组的Count属性,但通过强制转换为ICollection!

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中使用一系列很好的function:)