Count property vs Count() method?

后端 未结 8 2219
孤街浪徒
孤街浪徒 2020-11-27 04:21

Working with a collection I have the two ways of getting the count of objects; Count (the property) and Count() (the method). Does anyone know what

8条回答
  •  春和景丽
    2020-11-27 04:56

    Decompiling the source for the Count() extension method reveals that it tests whether the object is an ICollection (generic or otherwise) and if so simply returns the underlying Count property:

    So, if your code accesses Count instead of calling Count(), you can bypass the type checking - a theoretical performance benefit but I doubt it would be a noticeable one!

    // System.Linq.Enumerable
    public static int Count(this IEnumerable source)
    {
        checked
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }
            ICollection collection = source as ICollection;
            if (collection != null)
            {
                return collection.Count;
            }
            ICollection collection2 = source as ICollection;
            if (collection2 != null)
            {
                return collection2.Count;
            }
            int num = 0;
            using (IEnumerator enumerator = source.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    num++;
                }
            }
            return num;
        }
    }
    

提交回复
热议问题