C# 7.0 แนะนำการจับคู่รูปแบบในสองกรณี คือ นิพจน์และคำสั่งสวิตช์
รูปแบบจะทดสอบว่าค่ามีรูปร่างที่แน่นอน และสามารถดึงข้อมูลออกจากค่าได้เมื่อมีรูปร่างที่ตรงกัน
การจับคู่รูปแบบให้ไวยากรณ์ที่กระชับยิ่งขึ้นสำหรับอัลกอริทึม
คุณสามารถทำการจับคู่รูปแบบกับข้อมูลประเภทใดก็ได้ แม้กระทั่งของคุณเอง ในขณะที่ Withif/else คุณต้องมีการจับคู่ข้อมูลพื้นฐานเสมอ
การจับคู่รูปแบบสามารถดึงค่าจากนิพจน์ของคุณได้
ก่อนการจับคู่รูปแบบ −
ตัวอย่าง
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();
}
} ผลลัพธ์
Area of Rect 402.59999999999997 Area of Rect 536.8 Area of Circle 452.44799423217773
หลังการจับคู่รูปแบบ −
ตัวอย่าง
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();
}
} ผลลัพธ์
Area of Rect 402.59999999999997 Area of Rect 536.8 Area of Circle 452.44799423217773