
C# 7.0 在两种情况下引入了模式匹配:is 表达式和 switch 声明。
模式测试一个值是否具有一定的形状,并且可以从 具有匹配形状时的值。
模式匹配为算法提供了更简洁的语法
您可以对任何数据类型(甚至是您自己的数据类型)执行模式匹配,而 if/else,你总是需要基元来匹配。
模式匹配可以从表达式中提取值。
模式匹配之前 -
网站模板是能够具有交互性,能够包含更多活跃的元素,就有必要在网页中嵌入其它的技术。如:Javascript、VBScript、Document Object Model(DOM,文档对象模型)、Layers和 Cascading Style Sheets(CSS,层叠样式表),这里主要讲Javascript。那么Javascript是什么东西?Javascript就是适应动态网页制作的需要而诞生的
70
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
以上就是C# 7.0 中的模式匹配是什么?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号