C# switch 完整教程
·
一、基础 switch(传统语法)
语法格式
csharp
运行
switch (表达式)
{
case 常量1:
代码;
break; // 必须加,防止穿透
case 常量2:
代码;
break;
default: // 可选,匹配不到时执行
默认代码;
break;
}
示例:判断数字
csharp
运行
int num = 2;
switch (num)
{
case 1:
Console.WriteLine("数字1");
break;
case 2:
Console.WriteLine("数字2");
break;
case 3:
Console.WriteLine("数字3");
break;
default:
Console.WriteLine("其他数字");
break;
}
1. 多条件合并(多个 case 共用代码)
csharp
运行
int score = 85;
switch (score / 10)
{
case 10:
case 9:
Console.WriteLine("优秀");
break;
case 8:
case 7:
Console.WriteLine("良好");
break;
default:
Console.WriteLine("及格或不及格");
break;
}
2. 字符串匹配
csharp
运行
string str = "admin";
switch (str)
{
case "admin":
Console.WriteLine("管理员");
break;
case "user":
Console.WriteLine("普通用户");
break;
}
二、switch 穿透(不用 break)
C# 不允许自动穿透,只能用 goto case 手动穿透
csharp
运行
int n = 2;
switch (n)
{
case 1:
Console.WriteLine("1");
goto case 2; // 跳到case2
case 2:
Console.WriteLine("2");
break;
}
三、C# 8.0+ switch 表达式(极简,常用)
直接返回值,不需要 break,用 =>
csharp
运行
int level = 3;
string msg = level switch
{
1 => "一级",
2 => "二级",
3 => "三级",
_ => "未知" // _ 等价 default
};
Console.WriteLine(msg);
多条件范围匹配(when 筛选)
csharp
运行
int age = 20;
string tip = age switch
{
< 18 => "未成年",
>= 18 and < 60 => "成年人",
_ => "老年人"
};
四、switch 模式匹配(匹配对象 / 类型)
1. 匹配类型
csharp
运行
object obj = "hello";
string res = obj switch
{
int i => $"整数:{i}",
string s => $"字符串:{s}",
_ => "未知类型"
};
2. 匹配属性(属性模式)
csharp
运行
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Person p = new Person { Name = "张三", Age = 22 };
string info = p switch
{
{ Age: < 18 } => "少年",
{ Name: "张三", Age: > 20 } => "成年张三",
_ => "其他人"
};
五、switch 关键规则
- 传统
switch case结尾必须break,否则编译报错; switch支持:int、string、bool、enum等常量;- switch 表达式适合根据条件返回一个值,代码更简洁;
_在 switch 表达式中代表所有其他情况,替代 default;- C# 7 开始支持模式匹配、when 条件筛选。
六、enum 枚举搭配 switch
csharp
运行
enum Week { Mon, Tue, Wed }
Week w = Week.Mon;
switch (w)
{
case Week.Mon:
Console.WriteLine("周一");
break;
}更多推荐
所有评论(0)