如何要求用户只输入整数?

How to ask the user to input numbers only in integer?

我想要求用户输入一个数字,包括一个 if 语句选项,如果他输入字母,最后一个问题将被再次询问 我已经试过了,但似乎只对字符串有效

        Console.Write("Write a number:");
        int num = Convert.ToInt32(Console.ReadLine());

        if (!int.TryParse(age, out num))
            while(!int.TryParse(age, out num))
            {
             Console.WriteLine(...);
             // ....
            }

我在当前项目中使用的一个函数可能对您有所帮助,它只是检查输入字符串是否仅包含数字:

bool isDigitsOnly(string inputString)
{
    foreach (char c in inputString)
    {
        if (c < '0' || c > '9')
            return false;
    }
    return true;
}

您可能需要稍微修改一下以满足您的需要,但它应该可以正常工作

让我们为此提取方法:我们将要求用户输入有效值,直到他或她提供为止。所以我们有一个 loop:

   private static int ReadInteger(string question) {
     // Keep asking...
     while (true) {
       if (!string.IsNullOrWhiteSpace(question))
         Console.WriteLine(question);

       // ... until valid value provided
       if (int.TryParse(Console.ReadLine(), out int result))
         return result;

       Console.WriteLine($"Sorry, not a valid integer value; please, try again."); 
     }
   }

那你就可以把它当作

   int age = ReadInteger("Please, input age");