checked如何使用

date
Aug 3, 2022
slug
10035
status
Published
tags
C#
summary
type
Post
from Mark J. Price的书的第125页。
有些overflow系统检测不到,可以悄悄产生,比如
int max = 500;
for (byte i = 0; i < max; i++)
{
WriteLine(i);
}
由于i的初始值为0,编译器不会检测到错误,但byte的最大值是255,255+1时,系统悄悄运行,会变为byte类型的最小值0,不会报错。所以此code不会停止, 只有checked可以检测到这种exception,然后再用try catch把exception丢出来。
using System.Text;
using static System.Console;
using static System.Convert;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            try
            {
                checked
                {
                    int max = 500;
                    for (byte i = 0; i < max; i++)
                    {
                        WriteLine(i);
                    }
                }
            }
            //catch(OverflowException)
            //{
            //    Console.WriteLine("Overflow");
            //}
            catch (Exception ex)
            {
                Console.WriteLine(ex.GetType());
                Console.WriteLine(ex.Message);
            }
        }
    }
}
如果i的初始值为255,程序如果+1,此时编译器就会报错,不让运行,这时候可以使用unchecked

© Wen Bo 2021 - 2025