切换到默认情况的切换

问题描述 投票:0回答:1

我不明白为什么我的开关盒不起作用。我正在尝试从Console.Read变量获取用户输入,该变量已转换为Int32,但开关直接跳到默认情况下。

主要方法:

    class Program {
    static void Main(string[] args) {
        Console.WriteLine("##############################################");
        Console.WriteLine("#                                            #");
        Console.WriteLine("#     1 - ADD ITEM       3 - VIEW ITEMS      #");
        Console.WriteLine("#     2 - EDIT ITEM      4 - DELETE ITEM     #");
        Console.WriteLine("#                                            #");
        Console.WriteLine("##############################################");

        // Get input from user
        int userChoice = Convert.ToInt32(Console.Read());

        // Call function that responds to user selection from main menu
        Functions function = new Functions();
        function.SelectFunction(userChoice);
    }
}

这是从名为Function的类中获取的switch方法:

public void SelectFunction(int choice) {
        switch (choice) {
            case 1:
                Console.WriteLine("ADD ITEM");
                /*Console.WriteLine("Please enter ID:");
                var id = Console.ReadLine();
                Console.Write("Item name: ");
                var name = Console.ReadLine();*/
                break;
            case 2:
                Console.WriteLine("EDIT ITEM");
                break;
            case 3:
                Console.WriteLine("VIEW ITEMS");
                break;
            case 4:
                Console.WriteLine("DELETE ITEM");
                break;
            default:
                Console.WriteLine("Input not found in any of the choices. Please try again.");
                Console.ReadKey();
                break;
        }
    }
c# switch-statement
1个回答
2
投票

Console.Read不是您想的那样

Console.Read Method

从标准输入流中读取下一个字符。

它返回字符的值

改用Console.ReadLine

Console.ReadLine Method

从标准输入流中读取下一行字符。

© www.soinside.com 2019 - 2024. All rights reserved.