首页 > 编程 > C# > 正文

checked与unchecked操作符

2023-05-08 19:02:32
字体:
来源:转载
供稿:网友

checked(已检验)——用于设置溢出检验上下文(overflow-checking context),控制对整型算术表达式中的操作和转换进行溢出检验,在出现溢出时会抛出异常。格式为:checked(表达式)或checked{语句块}。

unchecked(未检验)——用于设置溢出检验上下文(overflow-checking context),控制对整型算术表达式中的操作和转换不进行溢出检验,在出现溢出时不抛出异常,结果为截断后的整数。格式为:unchecked(表达式)或unchecked{语句块}。

例如:

class Test {
              static readonly int x = 1000000;
              static readonly int y = 1000000;
              static int F() {
                            return checked(x * y); // Throws OverflowException
              }
              static int G() {
                            return unchecked(x * y); // Returns -727379968
              }
              static int H() {
                            return x * y; // Depends on default
              }
        }

又例如:

try {
                            int i, i2 = int.MaxValue, i2 = 200;
                            i = checked(i1 * i2); 
              } catch(Exception e){
              //MessageBox.Show(e.ToString());
              Console.WriteLine(e.ToString());
         }

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表