什么是C#7.0中的模式匹配?
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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短