问题描述
处理集合我有两种获取对象计数的方法;Count
(属性)和 Count()
(方法).有谁知道主要区别是什么?
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 the key differences are?
我可能错了,但我总是在任何条件语句中使用 Count
属性,因为我假设 Count()
方法对集合,其中 Count
必须在我获取"之前已经分配.但这是一个猜测 - 我不知道如果我错了是否会影响性能.
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()
会抛出异常吗?因为我很确定 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.
推荐答案
反编译 Count()
扩展方法的源代码显示它测试对象是否为 ICollection
(通用或其他),如果是,则返回基础 Count
属性:
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:
因此,如果您的代码访问 Count
而不是调用 Count()
,您可以绕过类型检查 - 理论上的性能优势,但我怀疑这会是一个明显的一个!
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 属性与 Count() 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!