一、C# unchecked运算符

unchecked运算符用于取消整型算术运算和转换的溢出检查。

二、提示

默认情况下,都是unchecked选项。因此,只有在需要把几个未检查的代码行放在一个明确标记为checked的代码块中以后,才需要显式使用unchecked关键字。

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

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

运行结果:

x的值是:0

在本例中,不会抛出异常,但会丢失数据。因为byte的数据类型不能包含256,溢出的位会被丢掉,所以x变量得到的值是0。

 

相关文章:

  • 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
相关资源
相似解决方案