代码执行将如何在 asp.net C# 中完成(IF,否则 If ,IF ,IF)

本文关键字:IF 否则 If 执行 net asp 代码 | 更新日期: 2023-09-27 18:21:06

我正在开发一个 asp.net MVC 5 Web应用程序。 现在我有以下内容:-

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

那么这将如何在我的应用程序中执行呢?以下内容如下:-

    如果条件 1 通过,则永远不会检查条件 2,而条件 3 和条件 4
  1. 将始终被检查?如果条件 1 失败,则条件 2 将被检查,条件 3 和 4 将被检查?

代码执行将如何在 asp.net C# 中完成(IF,否则 If ,IF ,IF)

在代码中加入一些缩进将清除您的问题

// 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");

在您的示例中,如果条件为 true,则没有大括号来分隔要执行的语句块,因此 ifs 以第一个分号结尾。

condition1为真时,将评估 else 链中的任何内容,因为 condition34 上的 if 都依赖于condition1为假和condition2为真。

如果condition1为 false,则计算condition2,如果为 true,则代码将检查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 
}

始终检查 3 和 4。 1 被选中,如果为 true,则忽略 2,因为它处于else if下,但如果 1 是false那么 2 将被评估。