控制台中带有 try and catch 的简单菜单

Simple menu in console with try and catch

我正在研究如何创建一个简单的菜单,显示用户输入的数字。另外,我想捕获任何非数字输入并写一条错误消息。 我想做的另一件事是让控制台仅在用户按下任意键时退出,在显示输出后。

在我的场景中,我没有任何错误,但控制台只是关闭了。我尝试使用 Console.Read(); 但它并没有阻止它退出。

到目前为止,这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MenuTest2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Choose an option:");
            Console.WriteLine(" 1. Write Hello");
            Console.WriteLine(" 2. Write jacob");
            int choice = Console.Read();
            try
            {
                switch (choice)
                {
                    case 1:
                        Console.WriteLine("Case 1");
                        Console.ReadLine();
                        break;
                    case 2:
                        Console.WriteLine("Case 2");
                        break;
                    default:
                        Console.WriteLine("Null");
                        break;
                }
            }
            catch (FormatException)
            {
                Console.WriteLine("{0} is not an integer", choice);
            }
            finally
            {
                Console.WriteLine("Press enter to close...");
                Console.ReadLine();
            }
        }
    }
}

我建议您在选择 choice 时使用 ReadLine() 而不是 Read()。然后使用 Convert.ToInt32(choice) 将其转换为 int,并在你的 try catch 中捕获它。

控制台读取从您的输入流中获取单个字符,returns 等效的 int32。出于这个原因,我不希望抛出异常。正如其他答案所建议的那样,使用 ReadLine() 函数,因为这样可以更好地处理

string userInput = Console.ReadLine(); 
if (int.TryParse(userInput, out int choice)) 
{
    switch(choice)
    {
        //etc
    }

}
else 
{
    Console.WriteLine("Invalid - Choice not a numeric response");
}