配列の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
その説明はありますか?
解決
配列には、.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
インターフェースを実装しますが、 Count
プロパティを直接公開しません。 ICollection.Count
の explicit 実装は、MSDNドキュメントこちら。
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でも使用できる便利な関数が多数用意されました:)
所属していません StackOverflow