在C#中,unchecked和checked关键字用于控制整数类型的算术溢出检测。
示例代码:
int a = int.MaxValue; int b = 1; // unchecked运算 unchecked { int result = a + b; Console.WriteLine(result); // 输出-2147483648 } // checked运算 try { checked { int result = a + b; Console.WriteLine(result); } } catch (OverflowException ex) { Console.WriteLine("OverflowException: " + ex.Message); } 在上面的示例中,通过unchecked关键字执行整数运算时,结果会溢出但不会抛出异常;而通过checked关键字执行整数运算时,结果会溢出并抛出OverflowException异常。根据具体情况选择合适的关键字以确保程序的正确性和性能。