switch表達式在表達式上下文中提供了類似switch的語意。
switch是一個選擇語句,根據與匹配表達式的模式匹配,從候選清單中選擇一個單獨的switch部分來執行。
如果一個單獨的表達式需要與三個或更多條件進行測試,通常會使用switch語句作為if-else結構的替代方案。
新的switch寫法
var message = c switch{ Fruits.Red => "The Fruits is red", Fruits.Green => "The Fruits is green", Fruits.Blue => "The Fruits is blue" };
class Program{ public enum Fruits { Red, Green, Blue } public static void Main(){ Fruits c = (Fruits)(new Random()).Next(0, 3); switch (c){ case Fruits.Red: Console.WriteLine("The Fruits is red"); break; case Fruits.Green: Console.WriteLine("The Fruits is green"); break; case Fruits.Blue: Console.WriteLine("The Fruits is blue"); break; default: Console.WriteLine("The Fruits is unknown."); break; } var message = c switch{ Fruits.Red => "The Fruits is red", Fruits.Green => "The Fruits is green", Fruits.Blue => "The Fruits is blue" }; System.Console.WriteLine(message); Console.ReadLine(); } }
The Fruits is green The Fruits is green
以上是如何在 C# 8.0 中寫出新的 Switch 表達式?的詳細內容。更多資訊請關注PHP中文網其他相關文章!