你得到例外是因为Console.Readline总是返回一个字符串,然后将其传递给Convert.ToInt32 and Convert.ToInt32如果传入空字符串,则抛出异常。
这个简短的示例演示了您遇到的问题。
try {
Convert.ToInt32(""); // Let's see how ToInt32 behaves for empty strings
} catch (Exception ex ) {
Console.WriteLine($"{ex.GetType()} -> {ex.Message}");
}
Output:
System.FormatException -> Input string was not in a correct format.
可能的修复
像这样的事情应该有帮助。
var ageStr = Console.ReadLine();
int? age = !string.IsNullOrEmpty(ageStr)
? Int32.Parse(ageStr);
: null;
由于您正在处理用户输入int.TryParse可能是更好的候选人。
var ageStr = Console.ReadLine();
int age;
bool success = Int32.TryParse(ageStr, out age);
if( !success ) {
Console.WriteLine($"'{ageStr}' is not an acceptable value for age.");
}