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

snr*_*snr 24 c# checked

当我在寻找Count 和 Count() 之间的区别时,我想看一眼Count(). 我看到以下代码片段,我想知道为什么checked需要/需要关键字:

int num = 0;
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        num = checked(num + 1);
    }
    return num;
}
Run Code Online (Sandbox Code Playgroud)

源代码:

// 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 35

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