我将“Int.TryParse”更改为while,现在我的代码无效

时间:2012-08-26 11:25:12

标签: c# console while-loop

//the code  
parseAttempt = while (KeyBoardInput, out Response);

1 个答案:

答案 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.");
        }
    }
}