为什么 Count() 方法使用 "checked" 关键字?

Why does the Count() method use the "checked" keyword?

当我在看the difference between Count and Count()的时候,我想看一眼Count()的源代码。我看到了以下代码片段,其中我想知道为什么 checked 关键字是 necessary/needed:

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;
    }
}

因为它不想 return 在序列中有超过 20 亿个项目的事件中 return 一个负数 - 或者一个非负数但 在序列中有超过 40 亿个项目的情况下(甚至更不可能)的数字是错误的checked 将检测溢出情况。