如何在C#中回到代码的上一行重新执行?
C# 实现回到代码开头重复执行的方案
要实现回到代码开头重新执行的功能,核心是用循环结构把需要重复执行的逻辑包裹起来。以下是针对你代码的修改方案:
方案一:使用do-while循环(推荐)
do-while会先执行一次逻辑,再判断是否继续循环,适配你的场景:
bool keepRunning = true; do { int wants; Console.WriteLine("What do you need? 1 - Links, 2 - Tasks or 3 - Misc, 0 - Exit"); // 增加输入验证,避免非数字输入导致程序崩溃 if (!int.TryParse(Console.ReadLine(), out wants)) { Console.WriteLine("请输入有效的数字!"); continue; // 直接回到循环开头重新提问 } switch (wants) { case 0: keepRunning = false; // 设置循环终止条件 break; case 1: Console.WriteLine("The line"); break; case 2: Console.WriteLine("The line"); break; case 3: Console.WriteLine("You have none as of current sir"); break; default: Console.WriteLine("Then why are you here..."); Console.WriteLine("Because you cant decide?"); Console.WriteLine("That must be it"); // 无需额外操作,循环会自动回到开头 break; } } while (keepRunning);
关键说明:
- 用
do-while包裹提问和分支判断的全部逻辑,每次执行完后自动回到开头(除非用户输入0退出)。 - 新增
int.TryParse做输入验证,避免用户输入非数字时程序报错崩溃。 - 加入
case 0作为主动退出选项,让用户可以正常结束程序。
方案二:使用无限while循环
如果不需要提前定义终止变量,也可以用while(true)创建无限循环,在需要退出的地方直接终止:
while (true) { int wants; Console.WriteLine("What do you need? 1 - Links, 2 - Tasks or 3 - Misc, 0 - Exit"); if (!int.TryParse(Console.ReadLine(), out wants)) { Console.WriteLine("请输入有效的数字!"); continue; } switch (wants) { case 0: Console.WriteLine("程序结束"); return; // 直接退出Main方法,终止程序 case 1: Console.WriteLine("The line"); break; case 2: Console.WriteLine("The line"); break; case 3: Console.WriteLine("You have none as of current sir"); break; default: Console.WriteLine("Then why are you here..."); Console.WriteLine("Because you cant decide?"); Console.WriteLine("That must be it"); break; } }
关键说明:
while(true)会一直执行循环体,直到遇到return或break终止。- 这种写法更简洁,但需要明确的退出条件(比如
case 0里的return)。
内容的提问来源于stack exchange,提问作者null-specter
相关产品推荐
相关产品推荐

