用来处理多条件的定值判断。
switch(变量或者表达式的值)
{
case 值1:要执行的代码;
break;
case 值2:要执行的代码;
break;
case 值3:要执行的代码;
break;
........
default:要执行的代码;
break;
}
程序执行到switch处,首先将括号中变量或者表达式的值计算出来,然后拿着这个值依次跟每个case后面所带的值进行匹配,一旦匹配成功,则执行该case所带的代码,执行完成后,遇到break,跳出switch-case结构。
如果跟每个case所带的值都不匹配,就要看当前这个switch-case结构中是否存在default,如果有default,则执行default中的语句,如果没有default,则该switch-case什么都不做。
例如:用户输入年份,再输入月份后输出该月的天数;
static void Main(string[] args)
{
try
{
Console.WriteLine("请输入年份:");
int year = Convert.ToInt32(Console.ReadLine());
try
{
Console.WriteLine("请输入月份:");
int month = Convert.ToInt32(Console.ReadLine());
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
Console.WriteLine("本月共31天");
break;
case 4:
case 6:
case 9:
case 11:
Console.WriteLine("本月共30天");
break;
case 2:
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
{//判断闰年
Console.WriteLine("本月共29天");
}
else
{//如果不是则为平年
Console.WriteLine("本月共28天");
}
break;
default:
Console.WriteLine("输入的月份不符合实际,程序退出");
break;
}
}
catch
{
Console.WriteLine("月份输入有误,程序退出");
}
}
catch
{
Console.WriteLine("年份输入有误,程序退出");
}
}
用到过 做个笔记