Computer >> Máy Tính >  >> Lập trình >> C#

Làm thế nào để viết Biểu thức Chuyển đổi mới trong C # 8.0?

Biểu thức switch cung cấp ngữ nghĩa giống như switch trong ngữ cảnh biểu thức

switch là một câu lệnh lựa chọn chọn một phần switch duy nhất để thực thi từ danh sách các ứng cử viên dựa trên đối sánh mẫu với biểu thức đối sánh.

Câu lệnh switch thường được sử dụng để thay thế cho cấu trúc if-else nếu một biểu thức duy nhất được kiểm tra với ba điều kiện trở lên.

Ví dụ

Cách viết công tắc mới

var message = c switch{
   Fruits.Red => "The Fruits is red",
   Fruits.Green => "The Fruits is green",
   Fruits.Blue => "The Fruits is blue"
};

Ví dụ 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();
   }
}

Đầu ra

The Fruits is green
The Fruits is green