C# 如何重构包含switch的代码以消除GOTO语句实现等效逻辑
解决方案
核心思路是用死循环+主动退出逻辑替代goto跳转,只有当用户输入合法的是/否选项时才退出循环,否则自动回到输入步骤重试,重构后的代码如下:
public static void One() { string response; Console.BackgroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Yellow; Console.Clear(); Console.WriteLine("Some text."); // 用死循环替代goto标签跳转 while (true) { Console.ReadKey(); Console.Write("\nA question?"); response = Console.ReadLine().ToLower(); Console.Clear(); switch (YesOrNoDetector.Detect(response)) { case YesOrNo.Yes: Console.WriteLine("A response!"); Console.ReadKey(); Two(); // 执行完Yes分支逻辑后直接退出当前方法,终止循环 return; case YesOrNo.No: Console.WriteLine("A different response."); Console.ReadKey(); Three(); // 执行完No分支逻辑后直接退出当前方法,终止循环 return; case YesOrNo.Undefined: Console.WriteLine("Refresh switch to look for a yes/no answer"); // 不添加额外退出逻辑,循环自动回到输入步骤重试 break; } } }
复用优化(适用于大量同类询问场景)
如果项目中有多处需要询问用户是/否的逻辑,可以把通用流程抽成公共方法,减少重复代码:
/// <summary> /// 通用是/否询问方法 /// </summary> /// <param name="question">要询问的问题文本</param> /// <param name="onYes">用户选Yes时执行的逻辑</param> /// <param name="onNo">用户选No时执行的逻辑</param> public static void AskYesNo(string question, Action onYes, Action onNo) { while (true) { Console.ReadKey(); Console.Write($"\n{question}"); string response = Console.ReadLine().ToLower(); Console.Clear(); switch (YesOrNoDetector.Detect(response)) { case YesOrNo.Yes: onYes(); return; case YesOrNo.No: onNo(); return; case YesOrNo.Undefined: Console.WriteLine("请输入有效的是/否选项"); break; } } }
封装后原One方法可以简化为:
public static void One() { Console.BackgroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Yellow; Console.Clear(); Console.WriteLine("Some text."); AskYesNo("A question?", () => { Console.WriteLine("A response!"); Console.ReadKey(); Two(); }, () => { Console.WriteLine("A different response."); Console.ReadKey(); Three(); }); }
内容的提问来源于stack exchange,提问作者labmate
相关产品推荐
相关产品推荐

