代码之家  ›  专栏  ›  技术社区  ›  Ahmed

我不能访问数组的Count属性,只能通过强制转换到ICollection!

  •  1
  • Ahmed  · 技术社区  · 15 年前
            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
    

    你对此有什么解释吗?

    3 回复  |  直到 15 年前
        1
  •  6
  •   Marc Gravell    15 年前

    数组有.length,而不是.count。

    但这是可用的(作为 显式接口实现 )关于收集等。

    基本上,与以下内容相同:

    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
    
        2
  •  3
  •   VVS    15 年前

    同时 System.Array 实施 ICollection 接口,它不会直接公开 Count 财产。你可以看到 明确的 执行 ICollection.Count 在msdn文档中 here .

    同样适用于 IList.Item .

    查看此日志,了解有关显式和隐式接口实现的更多详细信息: Implicit and Explicit Interface Implementations

        3
  •  1
  •   dan richardson    15 年前

    虽然这不能回答你的问题 直接地 ,如果使用.NET 3.5,则可以包括命名空间;

    using System.Linq;
    

    这将允许您使用count()方法,类似于将int数组强制转换为ICollection。

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

    然后,您还可以在LINQ中使用大量漂亮的函数:)