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

Ahm*_*aid 1 c# arrays 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
Run Code Online (Sandbox Code Playgroud)

你对此有解释吗?

Mar*_*ell 6

数组有.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
}
Run Code Online (Sandbox Code Playgroud)

Bar没有公共Foo财产 - 但如果您投射到IFoo以下情况,则可以使用

    Bar bar = new Bar();
    Console.WriteLine(bar.Value); // but no Foo
    IFoo foo = bar;
    Console.WriteLine(foo.Foo); // but no Value
Run Code Online (Sandbox Code Playgroud)