C# Switch 语句进阶:模式匹配详解与实例演示

开发 后端
模式匹配使得Switch语句更为强大,能够更直观地表达条件逻辑。不同的模式适用于不同的场景,根据需求选择合适的模式,提高代码的可读性和可维护性。使用模式匹配可以减少代码中的重复,并提供更灵活的条件判断方式。

在C#中,switch语句的模式匹配在C# 7.0及以上版本中引入。以下是switch语句中常见的模式及其使用方法的示例:

1. 类型模式:

优点: 用于检查对象的运行时类型,使代码更具可读性。

public static string GetObjectType(object obj)
{
    switch (obj)
    {
        case int i:
            return "整数类型";
        case string s:
            return "字符串类型";
        case double d:
            return "双精度浮点数类型";
        default:
            return "其他类型";
    }
}

2. 常量模式:

优点: 用于匹配对象是否等于某个常量值。

public static string GetDayOfWeekName(DayOfWeek day)
{
    switch (day)
    {
        case DayOfWeek.Monday:
            return "星期一";
        case DayOfWeek.Tuesday:
            return "星期二";
        case DayOfWeek.Wednesday:
            return "星期三";
        case DayOfWeek.Thursday:
            return "星期四";
        case DayOfWeek.Friday:
            return "星期五";
        default:
            return "其他";
    }
}

3. 组合模式:

优点: 允许将多个模式组合在一起,形成更复杂的匹配条件。

public static string GetInfo(object obj)
{
    switch (obj)
    {
        case int i when i > 0:
            return "正整数";
        case int i when i < 0:
            return "负整数";
        case string s when s.Length > 10:
            return "字符串长度大于10";
        default:
            return "其他";
    }
}

4. 属性模式:

优点: 用于匹配对象的属性,提供更灵活的条件判断。

public static string GetPersonInfo(object person)
{
    switch (person)
    {
        case { Age: > 18, Name: "Alice" }:
            return "成年人 Alice";
        case { Age: > 18, Name: "Bob" }:
            return "成年人 Bob";
        case { Age: <= 18, Name: "Alice" }:
            return "未成年人 Alice";
        default:
            return "其他";
    }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

5. 变量模式:

优点: 允许在模式中引入新的变量,提供更灵活的条件判断。

public static string GetVariablePattern(object obj)
{
    switch (obj)
    {
        case int i when i > 0:
            return $"正整数:{i}";
        case int i when i < 0:
            return $"负整数:{i}";
        case string s:
            return $"字符串:{s}";
        default:
            return "其他";
    }
}
  • 模式匹配使得switch语句更为强大,能够更直观地表达条件逻辑。
  • 不同的模式适用于不同的场景,根据需求选择合适的模式,提高代码的可读性和可维护性。
  • 使用模式匹配可以减少代码中的重复,并提供更灵活的条件判断方式。
责任编辑:姜华 来源: 今日头条
相关推荐

2009-08-18 13:30:01

C#安装与部署

2009-08-20 14:45:13

C# Switch语句

2009-09-01 18:29:10

C#继承C#多态

2009-09-07 14:33:02

C# switch语句

2009-08-18 10:17:25

C#枚举类型

2009-08-13 18:26:35

C#继承构造函数

2009-08-26 15:35:59

C#虚函数

2009-09-02 17:12:06

C#关机代码

2009-08-20 11:01:51

C#操作内存

2009-08-18 10:14:19

C#插件构架

2009-09-11 12:31:52

C#实例详解TypeConvert

2009-08-25 18:04:30

C#实现Singlet

2021-11-07 14:30:59

C++Switch语句

2021-06-04 08:34:55

C++线程编程开发技术

2009-08-18 17:05:08

C#操作xml文件

2009-08-28 12:47:30

C#静态方法应用

2009-08-28 13:12:56

C#反射实例C#反射

2009-09-01 11:25:08

C#读取Word文件

2009-08-21 10:13:02

C#异步初步

2009-08-26 11:32:37

C#打印文档
点赞
收藏

51CTO技术栈公众号