Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我无法访问数组的Count属性,但可以通过强制转换到ICollection!_C#_Arrays_Icollection - Fatal编程技术网

C# 我无法访问数组的Count属性,但可以通过强制转换到ICollection!

C# 我无法访问数组的Count属性,但可以通过强制转换到ICollection!,c#,arrays,icollection,C#,Arrays,Icollection,你对此有什么解释吗?数组有.Length,而不是.Count 但这在ICollection等上可用(作为显式接口实现) 本质上,与以下内容相同: int[] arr = new int[5]; Console.WriteLine(arr.Count.ToString());//Compiler Error Console.WriteLine(((ICollection)arr).Count.ToString());//works print 5

你对此有什么解释吗?

数组有.Length,而不是.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
Bar
没有公共的
Foo
属性-但如果您强制转换到
IFoo
,则该属性可用:

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

数组具有.Length,而不是.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
Bar
没有公共的
Foo
属性-但如果您强制转换到
IFoo
,则该属性可用:

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

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

这同样适用于IList.Item


有关显式和隐式接口实现的更多详细信息,请参阅本博客:

系统.Array
实现
ICollection
接口它不会直接公开
Count
属性。您可以在MSDN文档中看到
ICollection.Count
显式实现

这同样适用于IList.Item


有关显式和隐式接口实现的更多详细信息,请参阅本博客:

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

    Bar bar = new Bar();
    Console.WriteLine(bar.Value); // but no Foo
    IFoo foo = bar;
    Console.WriteLine(foo.Foo); // but no Value
然后,它允许您使用Count()方法,类似于将int数组转换为ICollection时的方法

using System.Linq;

然后,您还可以在Linq中使用一整套漂亮的函数:)

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

    Bar bar = new Bar();
    Console.WriteLine(bar.Value); // but no Foo
    IFoo foo = bar;
    Console.WriteLine(foo.Foo); // but no Value
这将允许您使用Count()方法,类似于将int数组强制转换为ICollection时

using System.Linq;

然后,您还可以在Linq中使用大量漂亮的函数:)

。。这将是O(n)而不是O(1)@VVS-你是不正确的。Enumerable.Count()在内部使用.Count检查ICollection。。。这将是O(n)而不是O(1)@VVS-你是不正确的。Enumerable.Count()在内部使用.Count检查ICollection。