把有点缩进你的代码会清除你的问题
// Test values, change them to change the output
int c1 = 1;
int c2 = 2;
int c3 = 3;
int c4 = 4;
if(c1 == 1)
Console.WriteLine("Condition1 is true");
else if (c2 == 2)
if(c3 == 3)
if(c4 == 4)
Console.WriteLine("Condition2,3 and 4 are true");
else
Console.WriteLine("Condition4 is false but 3 and 2 are true");
else
Console.WriteLine("Condition3 is false but 2 is true");
else
Console.WriteLine("Condition1 and 2 are false");
在您的例子有没有花括号来界定,如果条件为真要执行的语句块,所以IFS以第一个分号结尾。
当condition1
是在else链真正的什么都不会被评估,因为在condition3
和4
IFS都依赖于condition1
是假的,condition2
是真实的。
如果condition1
是假,那么condition2
进行评估,如果为真,代码去检查condition3
和去检查condition4
如果condition3
是真实的,
当然,这取决于你需要在执行何种措施输入值这可以简单地写为
if(c1 == 1)
Console.WriteLine("Condition1 is true");
else if (c2 == 2 && c3 == 3 && c4 == 4)
Console.WriteLine("Condition2,3, and 4 are true");
编辑
现在添加大括号后代码行为完全不同
if(condition1)
{
// enters here if condition1 is true, thus the condition2 is not evaluated
}
else if (condition 2)
{
// enters here if condition1 is evaluated and is false,
// but the condition2 is true
}
if(condition3)
{
// enters here if condition3 is true, indipendently from the
// result of the evaluation of condition1 and 2
}
if(condition4)
{
// enters here if condition3 is true, indipendently from the
// result of the evaluation of condition1 and 2
}
为什么你把它标记为asp.net? –
为什么不自己测试一下。 –
有没有在代码中使用括号或分号的原因?如果没有,它可能会被解释为与你想要的不同。 –