目录
????????switch语句是多路选择语句,它通过一个表达式的值来使程序从多个分支中选取一个用于执行的分支。
????????switch表达式的值只可以是整型、字符串、枚举和布尔类型。
????????switch语句中多个case可以使用一个break。
????????在switch多路选择语句中,多个case标签可以使用一个break关键字,但是只有最后一个case标签中可以带有语句块,而前面的case标签中不可以带有语句块内容。
// 使用switch多路选择语句判断季节
namespace _029
{
public partial class Form1 : Form
{
private Label? label1;
private ComboBox? comboBox1;
private Button? button1;
public Form1()
{
InitializeComponent();
Load += Form1_Load;
}
private void Form1_Load(object? sender, EventArgs e)
{
//
// label1
//
label1 = new Label
{
AutoSize = true,
Location = new Point(12, 16),
Name = "label1",
Size = new Size(43, 17),
TabIndex = 0,
Text = "选择月份:"
};
//
// comboBox1
//
comboBox1 = new ComboBox
{
FormattingEnabled = true,
Location = new Point(80, 8),
Name = "comboBox1",
Size = new Size(95, 25),
TabIndex = 1,
DropDownStyle = ComboBoxStyle.DropDownList //选择项只读
};
comboBox1.Items.AddRange([
"1月",
"2月",
"3月",
"4月",
"5月",
"6月",
"7月",
"8月",
"9月",
"10月",
"11月",
"12月"]);
//
// button1
//
button1 = new Button
{
Location = new Point(192, 10),
Name = "button1",
Size = new Size(75, 23),
TabIndex = 2,
Text = "判断季节",
UseVisualStyleBackColor = true
};
button1.Click += Button1_Click;
//
// Form1
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(279, 56);
Controls.Add(button1);
Controls.Add(comboBox1);
Controls.Add(label1);
Name = "Form1";
StartPosition = FormStartPosition.CenterScreen;
Text = "使用switch多路选择语句判断季节";
ResumeLayout(false);
PerformLayout();
}
private void Button1_Click(object? sender, EventArgs e)
{
switch (//跟据所选月份判断季节
comboBox1!.SelectedIndex + 1)
{
case 3:
case 4:
case 5:
MessageBox.Show("春季", "提示!");
break;
case 6:
case 7:
case 8:
MessageBox.Show("夏季", "提示!");
break;
case 9:
case 10:
case 11:
MessageBox.Show("秋季", "提示!");
break;
case 12:
case 1:
case 2:
MessageBox.Show("冬季", "提示!");
break;
default://如果没有选择月份弹出提示信息
MessageBox.Show("请选择月份", "提示!");
break;
}
}
}
}
?