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

问题描述 投票:2回答:1

[当我查看the difference between Count and 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;
    }
}
c# checked
1个回答
3
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.