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

WBOY
發布: 2023-08-25 18:57:02
轉載
1473 人瀏覽過

如何在 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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!