将字符串转换为Ints

Tak*_* M. 2 c# string int operators

好吧,小问题.我知道.基本的反应可能是

Convert.ToInt32(string);
Run Code Online (Sandbox Code Playgroud)

但很自然地,C#会做每一个自然过程以确保不会发生这种情况.

这是我的代码:

            while (true)
            {

                while (true)
                {
                    //ask for time
                    Console.WriteLine("What is the hour?");
                    Console.WriteLine();
                    string s = Console.ReadLine();
                    //convert input to int
                    YourTime.nHour = Convert.ToInt32(s);
                    //check to see if it's legal
                    if ((YourTime.nHour <= 12) || (YourTime.nHour > 0))
                    {
                        break;
                    }
                //etc etc code
                }
            }  
Run Code Online (Sandbox Code Playgroud)

我想确保输入是实际的小时.当我运行这段代码时,它总是将if()语句标记为"true"并中断,即使我输入的内容如-13或99.

我确信有一个简单的替换"Convert.ToInt32(s);",但说实话,我似乎已经尝试了一切.我决定最好按照知道手头代码的人的逐步说明进行操作.

[编辑] - 错误的操作员,而不是转换.感谢所有帮助过的人!

Red*_*ter 6

你需要使用AND而不是OR.所以,改成它

if ((YourTime.nHour <= 12) && (YourTime.nHour > 0)) 
Run Code Online (Sandbox Code Playgroud)