1
        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

その説明はありますか?

4

3 に答える 3

6

配列には.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
于 2009-06-23T09:47:59.700 に答える
3

インターフェイスをSystem.Array実装している間は、プロパティICollectionを直接公開しません。こちらのMSDNドキュメントでの明示的な実装をCount確認できます。ICollection.Count

同じことが。にも当てはまりますIList.Item

明示的および暗黙的なインターフェイスの実装の詳細については、このブログエントリを参照してください:暗黙的および明示的なインターフェイスの実装

于 2009-06-23T09:51:02.017 に答える
1

これはあなたの質問に直接答えることはありませんが、.NET 3.5を使用している場合は、名前空間を含めることができます。

using System.Linq;

これにより、int配列をICollectionとしてキャストする場合と同様に、Count()メソッドを使用できるようになります。

using System.Linq;

int[] arr = new int[5];
int int_count = arr.Count();

また、Linqでも使用できる多くの優れた関数があります:)

于 2009-06-23T09:53:43.667 に答える