一.基本用法

switch 语句是条件流程控制的一种方式,可以替代多重 if 语句。通过 switch 可以根据变量的不同取值执行不同的代码块。

示例:根据数字显示星期

int day = 8;
switch (day)
{
    case 1:
        Console.WriteLine("星期一");
        break;
    case 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:
        Console.WriteLine("输入星期有误");
        break;
}
  • 每个 case 表示变量的一种可能取值。
  • 每个 case 后需要加 break,否则会继续执行后续代码。
  • default 用于处理所有不在 case 中的情况

二.多个 case 合并写法

当多个 case 执行相同代码时,可以将它们合并,不需要在每个 case 后写 break。

int count = 4;
switch (count)
{
    case 1:
    case 2:
        Console.WriteLine("count==2");
        break;
    case 3:
        Console.WriteLine("count==3");
        break;
    default:
        break;
}

三.switch 支持字符串类型

switch 语句不仅可以用于数字类型,也支持字符串类型。

string name = "小张三";
switch (name)
{
    case "大山":
    case "小张":
    case "张三":
        Console.WriteLine("叫对了");
        break;
    default:
        Console.WriteLine("叫错了");
        break;
}

四.switch 支持枚举类型

枚举类型常用于表示一组有限的常量,switch 对枚举类型同样适用

Season 季节 = Season.Summer;
switch (季节)
{
    case Season.Spring:
        Console.WriteLine("春天");
        break;
    case Season.Summer:
        Console.WriteLine("夏天");
        break;
    case Season.Autumn:
        Console.WriteLine("秋天");
        break;
    case Season.Winter:
        Console.WriteLine("冬天");
        break;
    default:
        break;
}

枚举类型定义示例:

enum Season
{
    Spring, //春天
    Summer, //夏天
    Autumn, //秋天
    Winter  //冬天
}

五.实战:根据月份判断天数

利用 switch 可以实现根据用户输入的月份,判断该月的天数。

int day1 = 0;
Console.WriteLine("请输入月份:");
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:
        // 此处可扩展闰年判断
        day1 = 28;
        break;
    default:
        break;
}
Console.WriteLine($"当前是{month}月,本月有{day1}天");
  • 1、3、5、7、8、10、12 月份有 31 天
  • 4、6、9、11 月份有 30 天
  • 2 月份通常有 28 天(可扩展为闰年 29 天)

六.相关类型补充

1.枚举类型(enum):值类型,常用于定义一些常量;

2.结构体(struct):值类型;

3.类(class):引用类型;

// 结构体定义
struct People
{
}

// 类定义
class Student
{
}

小结

  • switch 是一种简洁高效的条件流程控制方式,适用于多分支选择场景。
  • 支持多种类型:整型、字符串、枚举等。
  • 合理利用 case 合并和 default,可以让代码更易读易维护。

更多推荐