c# checked unchecked 检查程序是否溢出
发布日期:2021-05-07 10:31:44 浏览次数:20 分类:精选文章

本文共 2485 字,大约阅读时间需要 8 分钟。

checked (操作符方式)

namespace ConsoleApp1{       class Program    {           static void Main(string[] args)        {               uint x = uint.MaxValue;            // 4294967295            Console.WriteLine(x);            string binStr = Convert.ToString(x, 2);            // 11111111111111111111111111111111            Console.WriteLine(binStr);            try            {                   // 这里会溢出,不checked处理,+1后会变成0                // 使用checked修饰符,会抛出 System.OverflowException: 算术运算导致溢出                uint y = checked(x + 1);                // 不会输出,因为产生了异常,跳转到了catch语句块                Console.WriteLine(y);            }            catch (OverflowException e)            {                   Console.WriteLine("有异常");            }            Console.WriteLine("程序继续执行");        }    }}//输出429496729511111111111111111111111111111111有异常程序继续执行

checked 方式2(上下文方式)

namespace ConsoleApp1{       class Program    {           static void Main(string[] args)        {               uint x = uint.MaxValue;            // 4294967295            Console.WriteLine(x);            string binStr = Convert.ToString(x, 2);            // 11111111111111111111111111111111            Console.WriteLine(binStr);            checked            {                   try                {                       uint y = x + 1;                    // 不会输出,因为产生了异常,跳转到了catch语句块                    Console.WriteLine(y);                }                catch (OverflowException e)                {                       Console.WriteLine("有异常");                }                Console.WriteLine("程序继续执行");            }        }    }}// 输出429496729511111111111111111111111111111111有异常程序继续执行

unchecked (操作符方式)

namespace ConsoleApp1{       class Program    {           static void Main(string[] args)        {               uint x = uint.MaxValue;            // 4294967295            Console.WriteLine(x);            string binStr = Convert.ToString(x, 2);            // 11111111111111111111111111111111            Console.WriteLine(binStr);            try            {               	// 因为使用了unchecked,这里不会有异常产生,可以不使用try来捕获异常            	// c#默认采用的就是unchecked模式                uint y = unchecked(x + 1);                // 0                Console.WriteLine(y);            }            catch (OverflowException e)            {                   Console.WriteLine("有异常");            }            Console.WriteLine("程序继续执行");        }    }}// 输出4294967295111111111111111111111111111111110程序继续执行

unchecked 方式2(上下文方式)

同理

上一篇:c# sizeof() 计算结构体所占的字节 And 自定义结构体
下一篇:c# 子类隐藏父类的方法 和 子类重写父类方法 的区别

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2025年03月26日 12时28分56秒