C#switch语句
·
第一段:switch 条件流程说明 + 星期判断
//switch 也是属于条件流程控制,可以替换if流程控制
int day = 8;
// 根据day进行显示不同周几
//sitch 选择
//() 具体的变量 根据哪个变量进行判断
//每个case 是变量一种可取情况
//每个case后面需要添加break进行跳出
switch (day)
{
case 1: //day==1
Console.WriteLine("星期一");
break;
case 2: // day==2
Console.WriteLine("星期二");
break;
case 3:
Console.WriteLine("星期三");
break;
case 4:
Console.WriteLine("星期四");
break;
case 5:
Console.WriteLine("星期五");
break;
case 6:
Console.WriteLine("星期六");
break;
case 7:
Console.WriteLine("星期天");
break;
default: // day!=1 2 3 4 5 6 7
Console.WriteLine("输入星期有误");
break;
}
第二段:多个 case 合并写法
int count = 4;
switch (count)
{
// 如果有俩个case执行的代码一样,可以把case写在一起 前面case就不要写break
case 1:
case 2:
Console.WriteLine("count==2");
break; //跳出流程控制 注意break后面不要写代码
//Console.WriteLine("");
case 3: // count ==3
Console.WriteLine("count==3");
break;
default:
break;
}
第三段:switch 匹配字符串类型
// switch() 可以跟字符串类型
string name = "小张三";
switch (name) // name有哪几种情况
{
case "大山": //如果name == 大山 、 小张 张三 执行逻辑一样
case "小张":
case "张三":
Console.WriteLine("叫对了");
break;
default:
Console.WriteLine("叫错了");
break;
}
第四段:switch 匹配枚举类型
//定义Season的枚举类型
Season 季节 = Season.Summer;// 季节就是变量 值是Season.Summer
switch (季节) // 可以是一个枚举类型
{
case Season.Spring:
Console.WriteLine("春天");
break;
case Season.Summer: // 季节==Season.Summer
Console.WriteLine("夏天");
break;
case Season.Autumn:
Console.WriteLine("秋天");
break;
case Season.Winter:
Console.WriteLine("冬天");
break;
default:
break;
}
第五段:switch 判断月份天数
//12月
//1 3 5 7 8 10 12 都是31天
//4 6 9 11 都是30天
//2 闰年29天 平年28天
int day1 = 0;
int month = int.Parse(Console.ReadLine()); // 输入月份
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day1 = 31;
break;
case 4:
case 6:
case 9:
case 11:
day1 = 30;
break;
case 2:
//if(是闰年){day1=29}else{day1=28}
day1 = 28;
break;
default:
break;
}
Console.WriteLine($"当前是{month}月,本月有{day1}天");
第六段:枚举、结构体、类 定义
// 枚举类型:值类型
enum Season
{
Spring,//春天
Summer,//夏天
Autumn,//秋天
Winter //冬天
}
// 结构体 值类型
struct People
{
}
//类 引用类型
class Student
{
}
更多推荐



所有评论(0)