在 .net 8中,switch 不需要再和传统的写法一样了,会更加的方便
创建一个 .net 8 控制台项目
switch 的写法没必要和以前一样
cs
namespace SwitchTest
{
internal class Program
{
static void Main(string[] args)
{
int day = 3;
var week = day switch
{
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
4 => "Thursday",
5 => "Friday",
_ => "oh shit"
} ;
Console.WriteLine(week);
}
}
}
运行:
如果将 day 设置为 30,在所有的选择中都找不到,那么结果就自动执行 _ 选项代码
cs
namespace SwitchTest
{
internal class Program
{
static void Main(string[] args)
{
int day = 30;
var week = day switch
{
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
4 => "Thursday",
5 => "Friday",
_ => "oh shit"
} ;
Console.WriteLine(week);
}
}
}
运行:
遍历枚举写法一样
cs
namespace SwitchTest
{
internal class Program
{
enum color { red, yellow, green }
static void Main(string[] args)
{
color myColos = color.red;
string colosStr = myColos switch
{
color.red => "红",
color.yellow => "黄",
color.green => "绿",
_ => throw new Exception()
} ;
Console.WriteLine(colosStr);
}
}
}
end