C# 我无法访问数组的Count属性,但可以通过强制转换到ICollection!
你对此有什么解释吗?数组有.Length,而不是.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
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。