C# .Net8 switch的用法小結(jié)
在 .net 8中,switch 不需要再和傳統(tǒng)的寫(xiě)法一樣了,會(huì)更加的方便
創(chuàng)建一個(gè) .net 8 控制臺(tái)項(xiàng)目
switch 的寫(xiě)法沒(méi)必要和以前一樣
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); } } }
運(yùn)行:
如果將 day 設(shè)置為 30,在所有的選擇中都找不到,那么結(jié)果就自動(dòng)執(zhí)行 _ 選項(xiàng)代碼
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); } } }
運(yùn)行:
遍歷枚舉寫(xiě)法一樣
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); } } }
到此這篇關(guān)于C# .Net8 switch的用法小結(jié)的文章就介紹到這了,更多相關(guān).Net8 switch內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C# 實(shí)現(xiàn)TXT文檔轉(zhuǎn)Table的示例代碼
這篇文章主要介紹了C# 實(shí)現(xiàn)TXT文檔轉(zhuǎn)Table的示例代碼,幫助大家更好的理解和學(xué)習(xí)c#,感興趣的朋友可以了解下2020-12-12C# Winform實(shí)現(xiàn)截圖工具的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何使用C# Winform制作一個(gè)簡(jiǎn)單的截圖工具,從而實(shí)現(xiàn)截圖功能,文中的示例代碼講解詳細(xì),有需要的可以參考下2024-02-02C# 實(shí)現(xiàn)在控制臺(tái)上換行輸出與不換行輸出
這篇文章主要介紹了C# 實(shí)現(xiàn)在控制臺(tái)上換行輸出與不換行輸出,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-04-04