Kru*_*zer 1 c# console if-statement tryparse
这是我使用Int32.TryParsewith if条件的代码片段.(控制台应用程序)
Console.WriteLine("Enter the no of the person(value for n)");
string number = Console.ReadLine();
Console.WriteLine("Enter the no of the bulb whose state you want to check(value for x)");
string bulbNumber = Console.ReadLine();
if ((Int32.TryParse(number, out n)) || (Int32.TryParse(bulbNumber, out x)))
{
}
Run Code Online (Sandbox Code Playgroud)
如果我们在quickwatch中检查n的值,那么它会正确捕获您输入的值,但如果您检查x的值,则会出乎意料地为0! - 任何想法如何克服这个?我想知道造成这种异常的原因.
您应该使用&&而不是||,"||" 是说如果一个是真的,哪一个是如此,它忽略了第二个.使用&&两者都必须是真的.
if ((Int32.TryParse(number, out n)) && (Int32.TryParse(bulbNumber, out x)))
{
//Go crazy
}
Run Code Online (Sandbox Code Playgroud)
您的原始代码意味着它会执行此操作:
首先是tryparse || 第二次tryparse
首先完成>直接进入if语句,忽略第二个已经过去.
使用&&它说两者都必须是真的.
有关此问题的更多信息,您可以使用MSDN查看条件语句中差异的示例: