如何重构switch case语句以处理自然语言形式的用户选择?
方案1:预定义匹配集合 + 条件模式匹配(兼容所有C#现代版本)
先把需要复用的case值预存为全局/类级别的只读集合,之后在任意switch语句中直接通过条件判断引用即可:
// 预定义可复用的匹配组,全局只需要定义一次 private static readonly HashSet<string> YesGroup = new HashSet<string> { "yes", "y", "yep", "yeah" }; private static readonly HashSet<string> NoGroup = new HashSet<string> { "no", "n", "nope", "nah" };
修改后的switch写法:
Console.Write("\nWere you feeling exhausted? "); response = Console.ReadLine().ToLower(); Console.Clear(); switch (response) { case var res when YesGroup.Contains(res): goto ThreeTwo; case var res when NoGroup.Contains(res): // 原有no分支逻辑 // ... }
这种写法和你原来写4个并列case的执行逻辑完全一致,后续要新增/修改yes/no的匹配值,只需要修改集合定义的位置即可,所有引用的switch都会自动生效。
方案2:C# 9+ 集合常量模式(语法更简洁)
如果你使用的是C# 9及以上版本,可以直接用集合常量模式进一步简化写法,不需要写when判断:
// 预定义常量匹配组 private const string[] YesGroup = ["yes", "y", "yep", "yeah"]; private const string[] NoGroup = ["no", "n", "nope", "nah"];
switch写法:
switch (response) { case YesGroup: goto ThreeTwo; case NoGroup: // no分支逻辑 }
方案3:封装为判断方法(逻辑复用更彻底)
如果需要在多个地方判断用户回复类型,还可以直接把判断逻辑封装为静态方法,连大小写转换、空值处理都可以一起封装:
public static class ResponseHelper { private static readonly HashSet<string> YesGroup = new HashSet<string> { "yes", "y", "yep", "yeah" }; private static readonly HashSet<string> NoGroup = new HashSet<string> { "no", "n", "nope", "nah" }; public static bool IsYes(string input) { return !string.IsNullOrEmpty(input) && YesGroup.Contains(input.ToLower()); } public static bool IsNo(string input) { return !string.IsNullOrEmpty(input) && NoGroup.Contains(input.ToLower()); } }
使用时可以直接在switch中引用,甚至不需要提前对输入做ToLower处理:
Console.Write("\nWere you feeling exhausted? "); response = Console.ReadLine(); Console.Clear(); switch (response) { case var res when ResponseHelper.IsYes(res): goto ThreeTwo; case var res when ResponseHelper.IsNo(res): // no分支逻辑 }
内容的提问来源于stack exchange,提问作者labmate
相关产品推荐
相关产品推荐

