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
その説明はありますか?
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
その説明はありますか?
配列には.Countではなく.Lengthがあります。
ただし、これは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
インターフェイスをSystem.Array
実装している間は、プロパティICollection
を直接公開しません。こちらのMSDNドキュメントでの明示的な実装をCount
確認できます。ICollection.Count
同じことが。にも当てはまりますIList.Item
。
明示的および暗黙的なインターフェイスの実装の詳細については、このブログエントリを参照してください:暗黙的および明示的なインターフェイスの実装
これはあなたの質問に直接答えることはありませんが、.NET 3.5を使用している場合は、名前空間を含めることができます。
using System.Linq;
これにより、int配列をICollectionとしてキャストする場合と同様に、Count()メソッドを使用できるようになります。
using System.Linq;
int[] arr = new int[5];
int int_count = arr.Count();
また、Linqでも使用できる多くの優れた関数があります:)