C# unchecked运算符

一、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。

原文地址:https://www.cnblogs.com/melao2006/p/4239483.html