在查看Count和Count()之间的区别时,我想看一看的源代码Count()
。我看到了以下代码片段,我想知道为什么checked
关键字是必需/必需的:
int num = 0;
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
num = checked(num + 1);
}
return num;
}
源代码:
// System.Linq.Enumerable
using System.Collections;
using System.Collections.Generic;
public static int Count<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
}
ICollection<TSource> collection = source as ICollection<TSource>;
if (collection != null)
{
return collection.Count;
}
IIListProvider<TSource> iIListProvider = source as IIListProvider<TSource>;
if (iIListProvider != null)
{
return iIListProvider.GetCount(onlyIfCheap: false);
}
ICollection collection2 = source as ICollection;
if (collection2 != null)
{
return collection2.Count;
}
int num = 0;
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
num = checked(num + 1);
}
return num;
}
}
2
.NET 4.0尚无此检查,而4.5有。这样做很可能是为了避免WinRT迭代器出现问题,请注意,它们使用uint。
—
汉斯(Hans)Passant