C# switch表达式:.NET 6新特性与代码优化技巧
1. switch表达式简介
在C
8.0中首次引入的switch表达式在.NET 6中得到了进一步优化和增强。与传统switch语句相比,switch表达式提供了更简洁、更功能性的语法,特别适合模式匹配场景。
主要优势:
– 更简洁的语法
– 表达式形式(可返回值)
– 更好的模式匹配支持
– 减少样板代码
2. 基础语法对比
传统switch语句
“`csharp
string result;
switch (value)
{
case 1:
result = “One”;
break;
case 2:
result = “Two”;
break;
default:
result = “Unknown”;
break;
}
“`
switch表达式(C# 8.0+)
“`csharp
var result = value switch
{
1 => “One”,
2 => “Two”,
_ => “Unknown”
};
“`
3. .NET 6中的增强特性
3.1 属性模式匹配
“`csharp
var shape = new Rectangle { Width = 10, Height = 20 };
var area = shape switch
{
{ Width: 0 } or { Height: 0 } => 0,
{ Width: var w, Height: var h } when w == h => w * h, // 正方形
{ Width: var w, Height: var h } => w * h // 长方形
};
“`
3.2 关系模式
“`csharp
string GetTemperatureDescription(double temp) => temp switch
{
“极寒”,
>= -10.0 and “寒冷”,
>= 0 and “凉爽”,
>= 15.0 and “舒适”,
>= 25.0 and “炎热”,
>= 35.0 => “酷热”,
double.NaN => “无效温度”
};
“`
3.3 列表模式匹配(C# 11/.NET 7预览)
“`csharp
int Sum(int[] values) => values switch
{
[] => 0,
[var first] => first,
[var first, .. var rest] => first + Sum(rest)
};
“`
4. 代码优化技巧
4.1 替代复杂if-else链
优化前:
“`csharp
if (employee is Manager m && m.Department == “IT”)
return 100000;
else if (employee is Developer d && d.YearsExperience > 5)
return 90000;
// …更多条件
“`
优化后:
“`csharp
var salary = employee switch
{
Manager { Department: “IT” } => 100000,
Developer { YearsExperience: > 5 } => 90000,
Developer => 70000,
_ => 50000
};
“`
4.2 与元组结合使用
“`csharp
var (a, b, op) = (10, 5, “+”);
var result = op switch
{
“+” => a + b,
“-” => a – b,
“*” => a * b,
“/” when b != 0 => a / b,
“/” => throw new DivideByZeroException(),
_ => throw new InvalidOperationException()
};
“`
4.3 模式匹配与解构
“`csharp
var shapes = new List { new Circle(5), new Rectangle(3, 4) };
var areas = shapes.Select(s => s switch
{
Circle c => Math.PI * c.Radius * c.Radius,
Rectangle r => r.Width * r.Height,
_ => 0
});
“`
5. 性能考量
switch表达式在大多数情况下与if-else链性能相当,但在以下场景可能有优势:
– 当JIT能优化为跳转表时
– 模式匹配比多重条件检查更清晰时
– 需要返回值而不是执行操作时
6. 最佳实践
1. 优先用于返回值的场景,而非执行操作
2. 对于复杂条件,考虑可读性胜过简洁性
3. 合理使用弃元模式(`_`)处理默认情况
4. 在.NET 6+中利用关系模式简化数值比较
5. 对null检查使用null模式:`null => …`
7. 总结
C
的switch表达式是.NET生态中越来越重要的特性,特别是在.NET 6及更高版本中。它通过:
– 减少样板代码
– 增强模式匹配能力
– 提供更函数式的编程风格
使代码更简洁、更易维护。
随着C
语言的演进,switch表达式将继续成为处理复杂条件逻辑的首选工具之一。
原文链接:https://www.g7games.com/65221.html 。如若转载,请注明出处:https://www.g7games.com/65221.html