C# .Net8 switch的用法小結
更新時間:2024年05月16日 11:44:31 作者:fkdw
在 .net 8中,switch 不需要再和傳統(tǒng)的寫法一樣了,會更加的方便,本文主要介紹了C# .Net8 switch的用法小結,具有一定的參考價值,感興趣的可以了解一下
在 .net 8中,switch 不需要再和傳統(tǒng)的寫法一樣了,會更加的方便
創(chuàng)建一個 .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,在所有的選擇中都找不到,那么結果就自動執(zhí)行 _ 選項代碼
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內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C# 實現(xiàn)TXT文檔轉(zhuǎn)Table的示例代碼
這篇文章主要介紹了C# 實現(xiàn)TXT文檔轉(zhuǎn)Table的示例代碼,幫助大家更好的理解和學習c#,感興趣的朋友可以了解下2020-12-12