C#if语句readline必须等于number

Zen*_*tie 1 c# string int

我无法弄清楚要放在括号中的内容,以便我的程序检查输入是否为数字.如果没有,我想返回错误,然后重新启动进程.有什么建议?

bool running = true;

Console.Write("Enter the number of victims so we can predict the next murder, Sherlock: ");

while (running)
{
    victimCount = int.Parse(Console.ReadLine());

    if (/*I want victimCount only to be accepted if it's a number*/)
    {
        Console.Write("\nThat's an invalid entry. Enter a correct number!: ");
    }
    else
    {
        running = false;
    }
}
Run Code Online (Sandbox Code Playgroud)

Son*_*nül 7

如果是一个数字,我希望仅接受victimCount

您可以使用int.TryParse方法代替.它返回boolean值是否有效的值int.

string s = Console.ReadLine();
int victimCount;
if(Int32.TryParse(s, out victimCount))
{
   // Your value is a valid int.
}
else
{
   // Your value is not a valid int.
}
Run Code Online (Sandbox Code Playgroud)

Int32.TryParse方法NumberStyles.Integer默认使用.这意味着你的字符串可以有;

作为一个数字.