目录
一、定义
二、示例:
三、生成:
一、定义
使用checked关键字处理溢出。
在进行数学运算时,由于变量类型不同,数值的值域也有所不同。如果变量中的数值超出了变量的值域,则会出现溢出情况,出现溢出时变量中的数值将不准确。怎样有效地防止溢出呢?下面结合实例演示怎样使用checked关键字检查是否出现溢出。
例如,数值类型为byte,byte类型的值域为0~255,所以如果byte类型变量的值高于255或者小于0都会出现溢出。
二、示例:
// 使用checked关键字判断是否有溢出
namespace _022
{
public partial class Form1 : Form
{
private Label? label1;
private Label? label2;
private Button? button1;
private TextBox? textBox1;
private TextBox? textBox2;
private TextBox? textBox3;
public Form1()
{
InitializeComponent();
Load += Form1_Load;
}
private void Form1_Load(object? sender, EventArgs e)
{
//
// label1
//
label1 = new Label
{
AutoSize = true,
Location = new Point(65, 18),
Name = "label1",
Size = new Size(43, 17),
TabIndex = 0,
Text = " + "
};
//
// label2
//
label2 = new Label
{
AutoSize = true,
Location = new Point(150, 18),
Name = "label2",
Size = new Size(43, 17),
TabIndex = 7,
Text = " = "
};
//
// button1
//
button1 = new Button
{
Location = new Point(247, 15),
Name = "button1",
Size = new Size(75, 23),
TabIndex = 3,
Text = "计算",
UseVisualStyleBackColor = true
};
button1.Click += Button1_Click;
//
// textBox1
//
textBox1 = new TextBox
{
Location = new Point(12, 15),
Name = "textBox1",
Size = new Size(50, 23),
TabIndex = 4,
Text = "100"
};
//
// textBox2
//
textBox2 = new TextBox
{
Location = new Point(99, 15),
Name = "textBox2",
Size = new Size(50, 23),
TabIndex = 5,
Text = "200"
};
//
// textBox3
//
textBox3 = new TextBox
{
Location = new Point(182, 15),
Name = "textBox3",
Size = new Size(50, 23),
TabIndex = 6
};
//
// Form1
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(334, 91);
Controls.Add(label2);
Controls.Add(textBox3);
Controls.Add(textBox2);
Controls.Add(textBox1);
Controls.Add(button1);
Controls.Add(label1);
Name = "Form1";
StartPosition = FormStartPosition.CenterScreen;
Text = "使用checked关键字处理溢出";
}
private void Button1_Click(object? sender, EventArgs e)
{
if (byte.TryParse( //对两个byte类型变量赋值
textBox1!.Text, out byte Add_One)
&& byte.TryParse(textBox2!.Text, out byte Add_Two))
{
try
{
checked { Add_One += Add_Two; } //使用checke关键字判断是否有溢出
textBox3!.Text = Add_One.ToString(); //输出相加后的结果
}
catch (OverflowException ex)
{
MessageBox.Show(ex.Message, "出错!"); //输出异常信息
}
}
else
{
MessageBox.Show("请输入255以内的数字!"); //输出错误信息
}
}
}
}
三、生成: