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

如何在C#控制台应用中从子菜单返回主菜单

问题:分页界面输入0返回主菜单而非退出程序

我开发的C#控制台应用包含菜单选项,用户选择选项2时进入分页模式查看产品。需要实现用户输入0时从分页界面返回主菜单,但当前输入0会直接退出程序,求修改方案。现有代码如下:

主菜单逻辑代码:

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    var shouldRun = true;
    DisplayOptions();

    while (shouldRun )
    {
        Console.Write("Enter an option: ");
        var input = Console.ReadKey();
        Console.WriteLine("\n");
        ConsoleKeyInfo selectedCurrency ;
        var currencyName = "USD";

        switch (input.Key)
        {
            case ConsoleKey.NumPad1:
            case ConsoleKey.D1:
                Console.WriteLine("Printing all products");
                OutputAllProduct(currencyName);
                break;
            case ConsoleKey.NumPad2:
            case ConsoleKey.D2:
                Console.WriteLine("Printing paginated products");
                OutputPaginatedProducts(); // 原代码此处方法名可能存在笔误,需与分页方法名一致
                break;                           
            case ConsoleKey.Q:
                shouldRun = false;
                break;
            default:
                Console.WriteLine("Invalid option!");
                break;
        }

        Console.WriteLine();
        DisplayOptions();
    }

    Console.Write("\n\rPress any key to exit!");
    Console.ReadKey();

   await _host.StopAsync(stoppingToken);
}

分页逻辑代码:

public void OutputPaginatedProducts()
{
    int totalPages = products.Count() / 5;
    do
    {
        Console.Write($"Please Enter Page number from 1 to {totalPages} or press 0 to exit\n");
        int pageNumber;

        if (int.TryParse(Console.ReadLine(), out pageNumber))
        {
            if (pageNumber >= 1 && pageNumber <= totalPages)
            {
                IEnumerable<Product> result = products.Skip((pageNumber - 1) * 5).Take(5);
                Console.WriteLine();
                Console.WriteLine("Displaying page: " + pageNumber);
                foreach (Product product in result)
                {
                    Console.WriteLine($"ID : {product.Id}\t Product Name : {product.ProductName}\tPrice : {product.Price} \tCurrency : {product.Price} {Currency.USD}");
                }
                Console.WriteLine();
            }
            else if(pageNumber==0)
            {
                Environment.Exit(0);
            }
        }
        else
        {
            Console.WriteLine($"Page number must be integer between 1 and {totalPages}");
        }
    } while (1==1);
}

修改方案

核心修改点:

  1. 移除Environment.Exit(0),改用布尔变量控制分页循环退出,从而回到主菜单
  2. 修复分页总数计算bug(当产品总数无法被5整除时,原计算方式会少算一页)

修改后的OutputPaginatedProducts方法代码:

public void OutputPaginatedProducts()
{
    // 修复分页总数计算:向上取整,确保所有产品都能分配到对应页面
    int productCount = products.Count();
    int totalPages = (productCount + 4) / 5;
    
    // 用布尔变量控制分页循环是否继续
    bool continuePaging = true;
    
    do
    {
        Console.Write($"Please Enter Page number from 1 to {totalPages} or press 0 to return to main menu\n");
        int pageNumber;

        if (int.TryParse(Console.ReadLine(), out pageNumber))
        {
            if (pageNumber >= 1 && pageNumber <= totalPages)
            {
                IEnumerable<Product> result = products.Skip((pageNumber - 1) * 5).Take(5);
                Console.WriteLine();
                Console.WriteLine("Displaying page: " + pageNumber);
                foreach (Product product in result)
                {
                    Console.WriteLine($"ID : {product.Id}\t Product Name : {product.ProductName}\tPrice : {product.Price} \tCurrency : {product.Price} {Currency.USD}");
                }
                Console.WriteLine();
            }
            else if(pageNumber == 0)
            {
                // 终止分页循环,回到主菜单
                continuePaging = false;
            }
            else
            {
                Console.WriteLine($"Invalid page number! Please enter a number between 1 and {totalPages}");
            }
        }
        else
        {
            Console.WriteLine($"Invalid input! Page number must be an integer between 1 and {totalPages}, or 0 to return to main menu");
        }
    } while (continuePaging); // 通过布尔变量控制循环持续
}

额外说明:

  • 主菜单代码中调用的方法名需与分页方法名保持一致(原代码中PaginatedProducts()应为OutputPaginatedProducts())
  • 修改后输入0会结束分页循环,方法执行完毕后自动回到主菜单循环,不会退出整个程序

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 01:31:21