C# .Net8 switch的用法小结
在 .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 => "Tuesdpythonay", 3 => "Wednesday", 4 => "Thursday", php 5 => "Friday", _ => "oh shit" } www.devze.com; 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", js 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 => "红", http://www.devze.com color.yellow => "黄", color.green => "绿", _ => throw new Exception() } ; Console.WriteLine(colosStr); } } }
到此这篇关于C# .Net8 switch的用法小结的文章就介绍到这了,更多相关.Net8 switch内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!
精彩评论