You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#代码中如何替代goto语句?新手编程技术求助

移除goto语句的重构方案

要替换代码里的goto,最直观的方式是用外层do-while循环来控制是否重新进入分类输入流程,这样逻辑更清晰,也符合结构化编程的规范。

核心思路:用一个布尔变量标记是否需要重试输入,当用户选择“N”时把标记设为true,触发循环再次执行;处理完“Y”的逻辑后标记设为false,直接退出循环。

重构后的完整代码:

bool shouldRetry;
do
{
    shouldRetry = false; // 默认不重试

    Console.WriteLine("New category");
    Console.WriteLine("***************************");
    Console.WriteLine();

    Console.Write("Name: ");
    string categoryName = Console.ReadLine();

    Console.WriteLine("Is this correct? (Y)es (N)o");

    Category category = new Category(categoryName);

    ConsoleKeyInfo userInput;
    bool invalidSelection;
    do
    {
        userInput = Console.ReadKey(true);
        invalidSelection = !(userInput.Key == ConsoleKey.Y || userInput.Key == ConsoleKey.N);
    } while (invalidSelection);

    var categoryExist = categoryList.Any(x => x.CategoryName == categoryName);

    switch (userInput.Key)
    {
        case ConsoleKey.Y:
            if (!categoryExist)
            {
                categoryList.Add(category);
                Console.Clear();
                Console.WriteLine("Category created!");
                Thread.Sleep(2000);
            }
            else
            {
                Console.Clear();
                Console.WriteLine("Category already exist");
                Thread.Sleep(2000);
                Console.Clear();
            }
            break;

        case ConsoleKey.N:
            Console.Clear();
            shouldRetry = true; // 标记需要重试,循环将重新执行输入流程
            break;
    }
} while (shouldRetry);

关键修改点:

  • 新增外层do-while循环,用shouldRetry变量控制循环生命周期
  • 移除原有的menu2:标签和goto menu2;语句
  • 在“N”分支中设置shouldRetry = true,触发重新输入流程
  • 每次进入循环时默认将shouldRetry设为false,确保正常处理完“Y”后能退出循环

内容的提问来源于stack exchange,提问作者DovNor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 10:00:58