模式匹配
C#的模式匹配扩展实现了函数式语言模式匹配的许多好处,但是以一种与底层语言的感觉平滑集成的方式
switch
表达
模式匹配扩展了 switch
语句以切换类型:
class Geometry {}
class Triangle : Geometry
{
public int Width { get; set; }
public int Height { get; set; }
public int Base { get; set; }
}
class Rectangle : Geometry
{
public int Width { get; set; }
public int Height { get; set; }
}
class Square : Geometry
{
public int Width { get; set; }
}
public static void PatternMatching()
{
Geometry g = new Square { Width = 5 };
switch (g)
{
case Triangle t:
Console.WriteLine($"{t.Width} {t.Height} {t.Base}");
break;
case Rectangle sq when sq.Width == sq.Height:
Console.WriteLine($"Square rectangle: {sq.Width} {sq.Height}");
break;
case Rectangle r:
Console.WriteLine($"{r.Width} {r.Height}");
break;
case Square s:
Console.WriteLine($"{s.Width}");
break;
default:
Console.WriteLine("<other>");
break;
}
}
is
表达
模式匹配扩展了 is
运算符以检查类型并同时声明一个新变量。
例
Version < 7
string s = o as string;
if(s != null)
{
// do something with s
}
可以改写为:
Version >= 7
if(o is string s)
{
//Do something with s
};
另请注意,模式变量 s
的范围扩展到 if
块之外,到达封闭范围的末尾,例如:
if(someCondition)
{
if(o is string s)
{
//Do something with s
}
else
{
// s is unassigned here, but accessible
}
// s is unassigned here, but accessible
}
// s is not accessible here