I can not access Count property of the array but through casting to ICollection !

こ雲淡風輕ζ 提交于 2019-12-02 11:19:30

问题


        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

Do you have an explanation for that?


回答1:


Arrays have .Length, not .Count.

But this is available (as an explicit interface implementation) on ICollection etc.

Essentially, the same as:

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

Bar doesn't have public a Foo property - but it is available if you cast to IFoo:

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



回答2:


While System.Array implement the ICollection interface it doesn't directly expose the Count property. You can see the explicit implementation of ICollection.Count in the MSDN documentation here.

The same applies to IList.Item.

Take look at this Blog entry for more details on explicit and implicit interface implementation: Implicit and Explicit Interface Implementations




回答3:


Whilst this doesn't answer your question directly, if you are using .NET 3.5 you can include the namespace;

using System.Linq;

which will then allow you to use a Count() method, similar to when casting your int array as an ICollection.

using System.Linq;

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

You also then have a whole host of nice functions you can use in Linq too :)



来源:https://stackoverflow.com/questions/1031583/i-can-not-access-count-property-of-the-array-but-through-casting-to-icollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!