//the code
parseAttempt = while (KeyBoardInput, out Response);
答案 0 :(得分:6)
您不能使用while循环替换 int.TryParse
,但您可以使用和 while循环使用,如下所示:
string keyboardInput = Console.ReadLine();
int response;
while (!int.TryParse(keyboardInput, out response)) {
Console.WriteLine("Invalid input, try again.");
keyboardInput = Console.ReadLine();
}
另一种方法是将代码重构为单独的方法:
int readIntFromConsole()
{
while (true)
{
string keyboardInput = Console.ReadLine();
int result;
if (int.TryParse(keyboardInput, out result))
{
return result;
}
else
{
Console.WriteLine("Invalid input, try again.");
}
}
}