C# 我怎样才能例外只允许数字?

C# How can I make an exception to allow only numbers?

这是我的代码

Console.WriteLine("Do you want to: 1. play against an Ai or 2. let two Ai´s play aigainst each other?");
Console.WriteLine("Please choose one option!");
 
int userInput = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("\n");

if (userInput == 1)
{
    // Player
    Player player = new Player();

我试图制作一个 try catch 块,但后来我在 if 语句中总是遇到 userInput 的问题。我想要一个 try .. catch 块来确保,如果用户输入字符或其他内容(+~#、...),他们会得到一个 错误消息,可以输入新内容。

我建议使用循环和 if 而不是 捕获异常 (异常是为 异常 情况设计的这种情况 - 我们应该只验证用户输入):

   int userInput = -1;

   // Keep on asking user until valid input is provided
   while (true) {
     Console.WriteLine("Do you want to:"); 
     Console.WriteLine("  1. play against an Ai or ");
     Console.WriteLine("  2. let two Ai´s play aigainst each other?");

     Console.WriteLine("Please choose one option!");

     // Trim() - let's be nice and tolerate leading and trailing spaces
     string input = Console.ReadLine().Trim();

     if (input == "1" || input == "2") {
       userInput = int.Parse(input);

       break;
     }
      
     Console.WriteLine("Sorry, invalid option. Please, try again.");
   }