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

Khớp mẫu trong C # 7.0 là gì?

C # 7.0 giới thiệu đối sánh mẫu trong hai trường hợp, biểu thức là và biểu thức chuyển đổi.

Các mẫu kiểm tra rằng một giá trị có hình dạng nhất định và có thể trích xuất thông tin từ giá trị khi nó có hình dạng phù hợp.

Đối sánh mẫu cung cấp cú pháp ngắn gọn hơn cho các thuật toán

Bạn có thể thực hiện đối sánh mẫu trên bất kỳ kiểu dữ liệu nào, thậm chí là của riêng bạn, trong khi với / khác, bạn luôn cần các nguyên mẫu để đối sánh.

Đối sánh mẫu có thể trích xuất các giá trị từ biểu thức của bạn.

Trước khi đối sánh mẫu -

Ví dụ

public class PI{
   public const float Pi = 3.142f;
}
public class Rectangle : PI{
   public double Width { get; set; }
   public double height { get; set; }
}
public class Circle : PI{
   public double Radius { get; set; }
}
class Program{
   public static void PrintArea(PI pi){
      if (pi is Rectangle){
         Rectangle rectangle = pi as Rectangle;
         System.Console.WriteLine("Area of Rect {0}", rectangle.Width * rectangle.height);
      }
      else if (pi is Circle){
         Circle c = pi as Circle;
         System.Console.WriteLine("Area of Circle {0}", Circle.Pi * c.Radius * c.Radius);
      }
   }
   public static void Main(){
      Rectangle r1 = new Rectangle { Width = 12.2, height = 33 };
      Rectangle r2 = new Rectangle { Width = 12.2, height = 44 };
      Circle c1 = new Circle { Radius = 12 };
      PrintArea(r1);
      PrintArea(r2);
      PrintArea(c1);
      Console.ReadLine();
   }
}

Đầu ra

Area of Rect 402.59999999999997
Area of Rect 536.8
Area of Circle 452.44799423217773

Sau khi đối sánh mẫu -

Ví dụ

public class PI{
   public const float Pi = 3.142f;
}
public class Rectangle : PI{
   public double Width { get; set; }
   public double height { get; set; }
}
public class Circle : PI{
   public double Radius { get; set; }
}
class Program{
   public static void PrintArea(PI pi){
      if (pi is Rectangle rectangle){
         System.Console.WriteLine("Area of Rect {0}", rectangle.Width *
         rectangle.height);
      }
      else if (pi is Circle c){
         System.Console.WriteLine("Area of Circle {0}", Circle.Pi * c.Radius *
         c.Radius);
      }
   }
   public static void Main(){
      Rectangle r1 = new Rectangle { Width = 12.2, height = 33 };
      Rectangle r2 = new Rectangle { Width = 12.2, height = 44 };
      Circle c1 = new Circle { Radius = 12 };
      PrintArea(r1);
      PrintArea(r2);
      PrintArea(c1);
      Console.ReadLine();
   }
}

Đầu ra

Area of Rect 402.59999999999997
Area of Rect 536.8
Area of Circle 452.44799423217773