一、C# checked运算符

checked运算符用于对整型算术运算和显式转换启用溢出检查。

默认情况下,表达式产生的值如果超出了目标类型的范围,将会产生两种情况:

?常数表达式将导致编译时错误。

?变量表达式在运行时计算并将引发异常。

二、提示

如果我们通过编译器选项或者环境配置在全局范围内取消了溢出检查,就可以使用checked关键字来启用该项功能了。

三、示例
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            // C# checked运算符-www.baike369.com
            byte x = 255;
            checked
            {
                x++;  // 超出了0至255的范围,溢出
            }
            Console.WriteLine("x的值是:" + x);
            Console.ReadLine();
        }
    }
}

运行上面的代码,将会产生“算术运算导致溢出”的错误信息。如下图所示:

C# checked运算符

byte数据类型只能包含0到255的整数,所以x值的加1会导致溢出。

相关文章:

  • 2021-06-09
  • 2021-07-21
  • 2021-11-05
  • 2021-09-05
  • 2022-01-25
  • 2021-07-19
猜你喜欢
  • 2021-12-19
  • 2021-11-24
  • 2022-12-23
  • 2021-11-11
  • 2021-08-31
  • 2021-12-16
  • 2021-06-18
相关资源
相似解决方案