模式匹配
模式匹配 是一种测试表达式是否具有特定特征的方法。
模式匹配 的类型:常量、类型、关系、模式、元组、属性、递归。
模式匹配 的表现形式
- if … else … 形式
- switch … case … 形式
- 超级 switch 形式
if..else..形式
C#
public record Book(string Title, string Author);
public static void PatternMatching(object? o)
{
if (o is null) // 常量匹配
{
throw new ArgumentNullException(nameof(o));
}
else if (o is int i) // 类型匹配
{
Console.WriteLine($"price is {i}");
}
else if (o is Book book) // 自定义类型匹配
{
Console.WriteLine(o);
}
}
switch 形式
C#
using static ConsoleApp1.Program.TrafficLight;
public enum TrafficLight { Red, Yellow, Green };
public static void SwitchMatching(TrafficLight? trafficLight)
{
switch (trafficLight)
{
case null:
Console.WriteLine("null emotion");
break;
case Red:
Console.WriteLine("红灯");
break;
case Green or Yellow:
Console.WriteLine("绿灯&黄灯");
break;
default:
break;
}
}
增强 switch 形式
上面的 switch..case..
语句可以简化为增强 switch 形式:
C#
public static string SwitchMatching1(TrafficLight? trafficLight) =>
trafficLight switch
{
null => "null",
Red => "红灯",
Green or Yellow => "路灯 or 黄灯",
_ => throw new InvalidOperationException() // 异常无效操作
};