我无法访问数组的Count属性,但通过强制转换为ICollection!
-
06-07-2019 - |
题
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
你对此有解释吗?
解决方案
数组有.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
}
Bar
没有公开的 Foo
属性 - 但是如果你转换为 IFoo
,它就可用了:
Bar bar = new Bar();
Console.WriteLine(bar.Value); // but no Foo
IFoo foo = bar;
Console.WriteLine(foo.Foo); // but no Value
其他提示
虽然这不能直接回答 的问题,但如果您使用的是.NET 3.5,则可以包含命名空间;
using System.Linq;
然后允许您使用Count()方法,类似于将int数组转换为ICollection时。
using System.Linq;
int[] arr = new int[5];
int int_count = arr.Count();
你也可以在Linq中使用一系列很好的功能:)
不隶属于 StackOverflow