2015-11-08 40 views
-5

我正在开发一个asp.net mvc 5 web应用程序。现在我有以下内容: -如何在asp.net c#中执行代码(IF,IF,IF,IF)

IF(condition1) 
{ 
//1 
} 
    else if (condition 2) 
{ 
//2 
} 
    IF(condition3) 
{ 
//3 
} 
    IF(condition4) 
{ 
//4 
} 

那么这将如何在我的应用程序内执行? 将遵循是如下: -

  1. 如果条件1过去了那么conditio2将永远不会被选中,而条件3 & condition4会经常进行检查?如果条件1失败,那么条件2将被检查,条件3 & 4将被检查?
+0

为什么你把它标记为asp.net? –

+1

为什么不自己测试一下。 –

+1

有没有在代码中使用括号或分号的原因?如果没有,它可能会被解释为与你想要的不同。 –

回答

2

把有点缩进你的代码会清除你的问题

// 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链真正的什么都不会被评估,因为在condition34 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 
} 
+0

我在括号中添加了方括号。 –

+1

好吧,现在是不同的。条件3和条件4不再与条件2的评估链接在一起,并且总是在条件1和条件2为假或真的情况下进行评估 – Steve

1

3和4将始终被检查。 1得到检查,如果为真,则2被忽略,因为它在else if之下,尽管如果1是false那么2将被评估。