首頁  >  文章  >  後端開發  >  如何在 C# 8.0 中寫出新的 Switch 表達式?

如何在 C# 8.0 中寫出新的 Switch 表達式?

WBOY
WBOY轉載
2023-08-25 18:57:021443瀏覽

如何在 C# 8.0 中编写新的 Switch 表达式?

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"
};

範例 1

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中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除