List<string> list = new List<string>() {"a","b","c"};
IEnumerable<string> enumerable = list;
int c1 = list.Count;
int c2 = list.Count();
int c3 = enumerable.Count();
最后3个陈述之间在性能和实施方面是否存在差异?将list.Count()执行得更糟或与list.Count相同,并且如果引用的类型为IEnumerable< string> ?
解决方法
让我们看看Reflector:
public static int Count<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
ICollection<TSource> is2 = source as ICollection<TSource>;
if (is2 != null)
{
return is2.Count;
}
ICollection is3 = source as ICollection;
if (is3 != null)
{
return is3.Count;
}
int num = 0;
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
num++;
}
}
return num;
}
因此,如果您的IEnumerable<T>实现了ICollection<T>或ICollection,它将返回Count属性.