Count属性VS计数()方法? [英] Count property vs Count() method?

查看:594
本文介绍了Count属性VS计数()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与收集工作,我有获取对象的计数的两种方式; COUNT(财产)和Count()方法。任何人都知道什么是关键的区别是?其中,作为计数必须已经事先给我分配我可能是错的,但我总是用Count属性在任何条件语句,因为我假设伯爵()方法执行某种对收集查询的越来越。但是,这是一个猜测 - 我不知道如果我错了性能会受到影响。

Working with a collection I have the two ways of getting the count of objects; Count (the property) and Count() the method. Anyone know what key differences are? I might be wrong, but I always use the Count property in any conditional statements because I'm assuming the Count() method performs some sort of query against the collection where as Count must have already been assigned prior to me 'getting.' But that's a guess - I don't know if performance will be affected if I'm wrong.

编辑:出那么好奇,将COUNT()抛出一个异常,如果集合为空?因为我是pretty确保Count属性只返回0。

Out of curiosity then, will Count() throw an exception if the collection is null? Because I'm pretty sure the Count property simply returns 0.

推荐答案

反编译来源为计数()扩展方法表明,它测试的对象是一个的ICollection (通用或其他方式),如果是直接返回底层计数属性:

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:

所以,如果你的code访问计数不是调用计数(),可以绕过类型检查 - 理论性能优势,但我怀疑这将是一个明显的有一个

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<TSource>(this IEnumerable<TSource> source)
{
    checked
    {
        if (source == null)
        {
            throw Error.ArgumentNull("source");
        }
        ICollection<TSource> collection = source as ICollection<TSource>;
        if (collection != null)
        {
            return collection.Count;
        }
        ICollection collection2 = source as ICollection;
        if (collection2 != null)
        {
            return collection2.Count;
        }
        int num = 0;
        using (IEnumerator<TSource> enumerator = source.GetEnumerator())
        {
            while (enumerator.MoveNext())
            {
                num++;
            }
        }
        return num;
    }
}

这篇关于Count属性VS计数()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆