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

打印 上一主题 下一主题

主题 864|帖子 864|积分 2594

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

优点: 用于检查对象的运行时类型,使代码更具可读性。
  1. public static string GetObjectType(object obj)
  2. {
  3.     switch (obj)
  4.     {
  5.         case int i:
  6.             return "整数类型";
  7.         case string s:
  8.             return "字符串类型";
  9.         case double d:
  10.             return "双精度浮点数类型";
  11.         default:
  12.             return "其他类型";
  13.     }
  14. }
复制代码
2. 常量模式:

优点: 用于匹配对象是否等于某个常量值。
  1. public static string GetDayOfWeekName(DayOfWeek day)
  2. {
  3.     switch (day)
  4.     {
  5.         case DayOfWeek.Monday:
  6.             return "星期一";
  7.         case DayOfWeek.Tuesday:
  8.             return "星期二";
  9.         case DayOfWeek.Wednesday:
  10.             return "星期三";
  11.         case DayOfWeek.Thursday:
  12.             return "星期四";
  13.         case DayOfWeek.Friday:
  14.             return "星期五";
  15.         default:
  16.             return "其他";
  17.     }
  18. }
复制代码
3. 组合模式:

优点: 允许将多个模式组合在一起,形成更复杂的匹配条件。
  1. public static string GetInfo(object obj)
  2. {
  3.     switch (obj)
  4.     {
  5.         case int i when i > 0:
  6.             return "正整数";
  7.         case int i when i < 0:
  8.             return "负整数";
  9.         case string s when s.Length > 10:
  10.             return "字符串长度大于10";
  11.         default:
  12.             return "其他";
  13.     }
  14. }
复制代码
4. 属性模式:

优点: 用于匹配对象的属性,提供更灵活的条件判断。
  1. public static string GetPersonInfo(object person)
  2. {
  3.     switch (person)
  4.     {
  5.         case { Age: > 18, Name: "Alice" }:
  6.             return "成年人 Alice";
  7.         case { Age: > 18, Name: "Bob" }:
  8.             return "成年人 Bob";
  9.         case { Age: <= 18, Name: "Alice" }:
  10.             return "未成年人 Alice";
  11.         default:
  12.             return "其他";
  13.     }
  14. }
  15. public class Person
  16. {
  17.     public string Name { get; set; }
  18.     public int Age { get; set; }
  19. }
复制代码

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



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

用多少眼泪才能让你相信

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表