Int.tryparse在If条件下无法正常工作 - 任何解释?

时间:2013-07-24 07:14:59

标签: c# if-statement console tryparse

以下是使用Int32.TryParse和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)))
{
}

如果我们在quickwatch中检查n的值,那么它会正确捕获您输入的值,但如果您检查x的值,则会出乎意料地为0! - 任何想法如何克服这个?我想知道造成这种异常的原因。

2 个答案:

答案 0 :(得分:5)

你应该使用&&而不是||,“||”是说如果一个是真的,哪一个是如此,它忽略了第二个。使用&&两者都必须是真的。

if ((Int32.TryParse(number, out n)) && (Int32.TryParse(bulbNumber, out x)))
{
      //Go crazy
}

您的原始代码意味着它会执行此操作:

首先是tryparse ||第二次tryparse

首先完成>直接进入if语句,忽略第二个已经过去。

使用&&它说必须都是真的。

有关此内容的更多信息,您可以使用MSDN查看条件语句中差异的示例:

&& operator

|| operator

答案 1 :(得分:2)

当然x的值是0,在解析为n后你已经在你的条件中得到了一个“真”,所以第二个tryparse永远不会被执行。如果你想确保两者都是可解析的,请使用和条件:

if ((Int32.TryParse(number, out n)) && (Int32.TryParse(bulbNumber, out x)))