C# 7.0에서는 is 표현식과 switch 문이라는 두 가지 경우에 패턴 일치를 도입했습니다.
패턴은 값이 특정 모양을 가지고 있는지 테스트하고 일치하는 모양을 가질 때 값에서 정보를 추출할 수 있습니다.
패턴 일치는 알고리즘에 대한 보다 간결한 구문을 제공합니다.
자신의 데이터 유형을 포함하여 모든 데이터 유형에 대해 패턴 일치를 수행할 수 있지만 if/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