【问题标题】:Why does the Count() method use the "checked" keyword?为什么 Count() 方法使用“checked”关键字?
【发布时间】:2020-07-06 00:49:42
【问题描述】:

当我在看the difference between Count and Count()时,我想看看Count()的源代码。我看到下面的代码 sn-p 我想知道为什么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;
    }
}

【问题讨论】:

  • .NET 4.0 还没有这个检查,4.5 有。这样做有点可能是为了避免WinRT iterators 出现问题,请注意他们使用 uint。

标签: c# checked


【解决方案1】:

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

【讨论】:

  • @DavidMårtensson C# 默认为unchecked;它可以通过编译器开关在全局级别默认翻转为checked,但坦率地说,我很少看到使用它,所以我认为建议C#“通常”在checked模式下运行是非常错误的;另请注意,unsafeunchecked 没有交互
  • 这对我来说是个新闻,我在编写之前在一个项目中对此进行了测试,C# 抱怨溢出,直到我添加了 unchecked ?编辑:找到我所看到的答案“对于常量表达式(可以在编译时完全评估的表达式),始终检查默认上下文。除非将常量表达式明确放置在未经检查的上下文中,否则在编译期间发生溢出表达式的-time 评估会导致编译时错误。"
  • @DavidMårtensson 啊,是的-很好的细微差别;我在谈论运行时;正如你所说:编译时间不同
  • 但是编译时间不适用于帖子的示例,所以我的评论不正确,我已将其删除。
猜你喜欢
  • 1970-01-01
  • 2018-02-11
  • 1970-01-01
  • 1970-01-01
  • 2011-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多