C# - 嵌套 if 语句

C# 中的嵌套 if 是指一个 if 语句作为另一个 if 语句的目标。嵌套 if 语句会在另一个 if 语句中指定一个 if 或 if-else 语句。

在 C# 中,嵌套 if-else 语句始终是合法的,这意味着您可以在一个 if 或 else if 语句中使用另一个 if 或 else if 语句。

语法

以下是 C# 嵌套 if 语句的语法 -

if( boolean_expression 1) {
   /* 当布尔表达式 1 为真时执行 */
   if(boolean_expression 2) {
      /* 当布尔表达式 2 为真时执行 */
   }
}

您可以嵌套 else if... else,就像嵌套 if 语句一样。

示例:嵌套 If 语句的使用

在下面的示例中,我们演示了如何在 C# 程序中使用嵌套 if 语句 -

using System;
namespace DecisionMaking {
   class Program {
      static void Main(string[] args) {
         //* 局部变量定义 */
         int a = 100;
         int b = 200;
         
         /* 检查布尔条件 */
         if (a == 100) {
            
            /* 如果条件为真,则检查以下内容 */
            if (b == 200) {
               /* 如果条件为真,则打印以下内容 */
               Console.WriteLine("Value of a is 100 and b is 200");
            }
         }
         Console.WriteLine("Exact value of a is : {0}", a);
         Console.WriteLine("Exact value of b is : {0}", b);
         Console.ReadLine();
      }
   }
}

Output

当编译并执行上述代码时,它会产生以下结果 -

Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200

示例:嵌套 else-if 语句

在此示例中,我们使用嵌套 else-if 语句以结构化的方式检查具有多个条件的学生成绩 -

using System;
public class Example
{
   public static void Main()
   {
      int marks = 85;
      
      if (marks >= 90)
      {
         Console.WriteLine("Grade: A+");
      }
      else if (marks >= 80)
      {
         Console.WriteLine("Grade: A");
         
         if (marks >= 85)
         {
            Console.WriteLine("Excellent Performance!");
         }
         else
         {
            Console.WriteLine("Good Job!");
         }
      }
      else if (marks >= 70)
      {
         Console.WriteLine("Grade: B");
      }
      else if (marks >= 60)
      {
         Console.WriteLine("Grade: C");
      }
      else
      {
         Console.WriteLine("Grade: F - Needs Improvement");
      }
   }
}

Output

以下是上述代码的输出 -

Grade: A
Excellent Performance!