使用checked关键字处理“溢出”错误

在进行算术运算时,可以使用checked关键字有效处理溢出错误,使用checked关键字可能对程序的性能会有一点点的影响,这是一种以牺牲性能换取健康的做法。

 1        private void button1_Click(object sender, RoutedEventArgs e)
 2         {
 3             byte bt_First, bt_Second;
 4             if (byte.TryParse(txtNum1.Text, out bt_First) && byte.TryParse(txtNum2.Text, out bt_Second))
 5             {
 6                 try
 7                 {
 8                     checked
 9                     {
10                         txtResult.Text = (bt_First + bt_Second).ToString();
11                     }
12                 }
13                 catch (OverflowException ex)
14                 {
15                     MessageBox.Show(ex.Message);
16                 }
17             }
18             else
19             {
20                 MessageBox.Show("请输入255以内的数字!");
21             }
22         }

原文地址:https://www.cnblogs.com/chenyongblog/p/3185957.html