short a = 32767;
short b = 32767;
short c = (short)(a + b);
Console.WriteLine(c);
结果c是-2,显然不对,关键是程序运行没提示错误,很可能处理结果bug出现。
try
{
short a = 32767;
short b = 32767;
short c = checked((short)(a + b));
Console.WriteLine(c);
}
catch (OverflowException e)
{
Console.WriteLine(e.Message);
}
用checked检查错误。