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

后端 未结 3 1484
遇见更好的自我
遇见更好的自我 2021-01-23 08:26
        int[] arr = new int[5];
        Console.WriteLine(arr.Count.ToString());//Compiler Error
        Console.WriteLine(((ICollection)arr).Count.ToString());//works p         


        
3条回答
  •  孤独总比滥情好
    2021-01-23 08:58

    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
    

提交回复
热议问题