在 .net 8中,switch 不需要再和传统的写法一样了,会更加的方便
创建一个 .net 8 控制台项目
switch 的写法没必要和以前一样
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,在所有的选择中都找不到,那么结果就自动执行 _ 选项代码
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); } } }
运行:
遍历枚举写法一样
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); } } }
到此这篇关于c# .net8 switch的用法小结的文章就介绍到这了,更多相关.net8 switch内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论