功能描述
用于对整型类型算术运算和转换显式启用溢出检查。
注意事项
1.如果不选择使用Check关键字,则会出现数值溢出,
2.如果使用Check关键字,当出现数值溢出时,会弹出报错信息。
程序演示
1.未使用Check关键字,会出现数值溢出
static void Main(string[] args)
{
int i = 10;
Console.WriteLine(2147483647 + i);
Console.ReadKey();
2.使用Check关键字,数值溢出时,会触发报错信息
int i = 10;
Console.WriteLine(checked(2147483647 + i));
Console.ReadKey();
3.使用 checked 启用运行时溢出检查。用到的方法有Try…Catch。
static int maxIntValue = 2147483647;
static int CheckMethod()
{
int z = 0;
try
{
z = checked(maxIntValue + 10);
}
catch (System.OverflowException e)
{
Console.WriteLine("Checked and Caught" + e.ToString());
}
return z;
}
static int UncheckedMethod()
{
int z = 0;
try
{
z = maxIntValue + 10;
}
catch(System.OverflowException e)
{
Console.WriteLine("Unchecked and Caught" + e.ToString());
}
return z;
}
static void Main()
{
Console.WriteLine("\nChecked output valuse is:{0}",CheckMethod());
Console.WriteLine("\nUnChecked output valuse is:{0}",
UncheckedMethod());
Console.ReadKey();
}