C# 未显示错误消息;不正确的转换

C# 未显示错误消息;不正确的转换,c#,C#,有人能给我解释一下为什么我的错误消息没有显示出来,以及为什么int newUserInput行出现格式不正确的错误吗?试试这个: Console.Write("Enter a limit to the prime numbers you want displayed: "); userInput = Console.ReadLine(); int newUserInput = Convert.ToInt32(userInput); if (!int.TryParse(userInput, o

有人能给我解释一下为什么我的错误消息没有显示出来,以及为什么
int newUserInput
行出现格式不正确的错误吗?

试试这个:

Console.Write("Enter a limit to the prime numbers you want displayed: ");
userInput = Console.ReadLine();

int newUserInput = Convert.ToInt32(userInput);

if (!int.TryParse(userInput, out newUserInput))
{
    Console.WriteLine("\nThe value entered must be a whole number. Please try again: ");
}
只需在这里执行您的工作
int.TryParse(userInput,out newUserInput)
,不要在
TryParse

之前对其进行转换,请尝试以下操作:

Console.Write("Enter a limit to the prime numbers you want displayed: ");
userInput = Console.ReadLine();

int newUserInput = Convert.ToInt32(userInput);

if (!int.TryParse(userInput, out newUserInput))
{
    Console.WriteLine("\nThe value entered must be a whole number. Please try again: ");
}
只需在这里执行您的工作
int.TryParse(userInput,out newUserInput)
,在
TryParse

这完全取决于您使用Console.ReadLine()发送的内容。

此外,请参见以下内容:

Convert.ToInt32
将在
Int32
的输入不正确时抛出
FormatException
。提及

另外,看起来您正在使用
TryParse
再次覆盖
Convert.Int32
。实际上,您不需要
Convert.Int32

Console.Write("Enter a limit to the prime numbers you want displayed: ");
userInput = Console.ReadLine();

int newUserInput;

if (!int.TryParse(userInput, out newUserInput))
{
    Console.WriteLine("\nThe value entered must be a whole number. Please try again: ");
}
这完全取决于您使用Console.ReadLine()发送的内容。

此外,请参见以下内容:

Convert.ToInt32
将在
Int32
的输入不正确时抛出
FormatException
。提及

另外,看起来您正在使用
TryParse
再次覆盖
Convert.Int32
。实际上,您不需要
Convert.Int32

Console.Write("Enter a limit to the prime numbers you want displayed: ");
userInput = Console.ReadLine();

int newUserInput;

if (!int.TryParse(userInput, out newUserInput))
{
    Console.WriteLine("\nThe value entered must be a whole number. Please try again: ");
}

可能不是在不知道input.Convert.ToInt32将引发异常的情况下,如果之后的if语句太晚,则崩溃已经发生。尝试将转换放在if-statement之后。然后,正如Lasse所说,您的TryParse太晚了。可能不是在不知道输入的情况下。Convert.ToInt32将引发异常,您的if语句太晚了,崩溃已经发生。尝试将转换放在if-statement之后。然后,正如Lasse所说,您的TryParse太晚了。太好了,谢谢!还有一件事:如果我想在进一步的if语句中使用
userInput
,我是否需要转换字符串,或者我可以只使用
newUserInput
?(如果有意义的话…@ElonMuskrat您应该使用
newUserInput
,如果
TryParse
成功,它已经包含解析值。太好了,谢谢!还有一件事:如果我想在进一步的if语句中使用
userInput
,我是否需要转换字符串,或者我可以只使用
newUserInput
?(如果有意义的话…@ElonMuskrat您应该使用
newUserInput
,如果
TryParse
成功,它已经包含解析值。