集合对象里面有一个属性Count,还有一个方法Count(),都是返回集合元素的个数,请问有区别吗?我个人感觉里面有点怪怪的,用属性Count似乎对一个动态变化的集合有可能不管用。

解决方案 »

  1.   

    count方法比count属性功能强大,动态变化count也是管用的,属性是你获取的时候才去执行计算操作
      

  2.   

    属性Count是List<T>自身的
    Count方法是静态类Enumerable中定义的,调用Count()时,实际是调用Enumerable.Count<TSource>
      

  3.   

    看MSDN,方法返回序列中数量
      

  4.   

    Cout是属性Count()是Linq方法。后者效率应该不高。前者返回一个记录下来的变量值,后者要调用迭代器数出来。
      

  5.   

    List<T>的定义如下:public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable所有的接口只出现 Count 只读属性,没有Count()方法,是你搞混了。
      

  6.   

    当然有Count()方法,我用.net3.5 版本。我用Count()后,程序里面的一个bug似乎已经修正,但还不能肯定。不能发图,否则就截图给你们看看
      

  7.   

    那是扩展方法,不是在List里面定义的。
      

  8.   

    using System.Linq; // 引用
     List<int> list=new List<int>();
     list.Count<int>(); //扩展方法 
      

  9.   

    那个是LINQ支持的一个扩展方法查询集合中对象数的多少。
      

  10.   

    属性Count是ICollection接口中的,实现了ICollection接口的类有此属性
    方法Count()实际上是Count<T>()的一种简写形式,他是静态类IEnumerable中的一个成员方法,在C#3.0版本及以后版本中出现,属于扩展方法,任何实现了IEnumerable<T>接口的类都有Count<T>()方法
    原型:static class IEnumerable
    {
       public static int Count<T>(this IEnumerable<T> a)
       {
         //....
       }
    }//List<int> list=new List<int>();
    //list.Count()等价于list.Count<int>()等价于IEnumerable.Count<int>(list)
      

  11.   

    Enumerable 定义中只有 GetEnumerator() 方法;但在System.Linq命名空间中有 static class Enumerable 的定义, 里边有大量的扩展方法 (extention methods),当这些扩展方法不能属于List<T>的原始定义。下边是微软类库里的static class Enumerable定义中的部分代码, 里边的Count<TSource>(this IEnumerable<TSource> source)是个扩展方法,不属于List<T>。
    namespace System.Linq
    {
        // Summary:
        //     Provides a set of static (Shared in Visual Basic) methods for querying objects
        //     that implement System.Collections.Generic.IEnumerable<T>.
        public static class Enumerable
        {
            // ...        public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer);
            public static int Count<TSource>(this IEnumerable<TSource> source);
            public static int Count<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
            public static IEnumerable<TSource> DefaultIfEmpty<TSource>(this IEnumerable<TSource> source);        // ...
        }
    }
      

  12.   

    补充一点,以便你早点结帖。想要知道一个方法是否是extention method,你只需要将鼠标停留在相应的方法名称上,微软的IntelliSense就会告诉你有关的信息。比方说,当你的鼠标停留在 .Count(), 提示会有如下信息:
        (extention)...
         Returns the number of elements in a sequence.
    而当鼠标停留在 .Count上面,会有一下信息:
        Gets the number of elements actually contained in the System.Collections.Generic.List<T>.总之,.Count()和.Count都可以用,他们之间也肯定有差别。如果你熟悉LINQ, 差别自然会懂。如果没有接触该过LINQ,你就用.Count。他们之间的差别是你在懂得LINQ的基础上才能解释。希望以上解释能对你有帮助。