c# 7.0模式匹配示例与详解

在 C# 7.0 中,模式匹配(Pattern Matching)功能得到了显著增强,主要引入了 is 表达式和 switch 语句的模式匹配扩展,使得代码更简洁、可读性更强。


一、is 表达式增强

1. 类型模式(Type Pattern)

if 语句中直接检查类型并声明变量,无需显式类型转换。

object obj = 42;

// C# 7.0 前
if (obj is int)
{
    int i = (int)obj;
    Console.WriteLine($"是整数: {i}");
}

// C# 7.0 后
if (obj is int i) // 检查类型并赋值给变量 i
{
    Console.WriteLine($"是整数: {i}");
}
2. 带条件的类型模式

结合条件表达式进一步过滤匹配结果。

object obj = 10;

if (obj is int number && number > 5)
{
    Console.WriteLine($"整数大于5: {number}");
}

二、switch 语句的模式匹配

C# 7.0 允许在 switchcase 中使用类型模式和条件,支持更灵活的分支逻辑。

1. 类型模式与 when 条件
public class Shape { }
public class Circle : Shape { public double Radius { get; set; } }
public class Rectangle : Shape { public double Width, Height; }

Shape shape = new Circle { Radius = 5 };

switch (shape)
{
    case Circle c when c.Radius > 10:
        Console.WriteLine($"大圆,半径: {c.Radius}");
        break;
    case Circle c:
        Console.WriteLine($"小圆,半径: {c.Radius}");
        break;
    case Rectangle r:
        Console.WriteLine($"矩形,面积: {r.Width * r.Height}");
        break;
    default:
        Console.WriteLine("未知形状");
        break;
}
2. var 模式

使用 var 匹配任意类型,结合 when 条件处理特定逻辑。

object value = "Hello";

switch (value)
{
    case int i:
        Console.WriteLine($"整数: {i}");
        break;
    case string s when s.Length > 5:
        Console.WriteLine($"长字符串: {s}");
        break;
    case var _ when value == null: // 匹配 null
        Console.WriteLine("值为空");
        break;
    default:
        Console.WriteLine("其他类型");
        break;
}

三、常量模式

匹配常量值,如字符串、数值或 null

object input = "hello";

switch (input)
{
    case "hello":
        Console.WriteLine("打招呼");
        break;
    case string s when s.Length == 0:
        Console.WriteLine("空字符串");
        break;
    case null:
        Console.WriteLine("输入为空");
        break;
}

四、实际应用场景示例

示例 1:处理多种数据类型
public static void PrintInfo(object obj)
{
    if (obj is null) // 显式处理 null
    {
        Console.WriteLine("对象为空");
    }
    else if (obj is int i)
    {
        Console.WriteLine($"整数: {i}");
    }
    else if (obj is string s)
    {
        Console.WriteLine($"字符串长度: {s.Length}");
    }
}
示例 2:订单折扣计算
public class Order { public bool IsVIP { get; set; } }

public decimal CalculateDiscount(Order order, decimal price)
{
    switch (order)
    {
        case var _ when price > 1000:
            return price * 0.2m;
        case var o when o.IsVIP:
            return price * 0.1m;
        default:
            return 0;
    }
}

你可能感兴趣的:(C#,c#)