C# - if...else 语句

if-else 语句是一个条件语句,根据条件的真假执行不同的代码块。当条件为 true 时,将执行 if 语句;如果条件为 false,则执行 else 语句。

if 语句后可以跟一个可选的 else 语句,当布尔表达式为 false 时,将执行该语句。

语法

以下是 C# 中 if...else 语句的语法 -

if(boolean_expression) {
   /* 如果布尔表达式为真,则语句将执行 */
} else {
   /* 
   如果布尔表达式为假,则执行语句
   */
}

如果布尔表达式的计算结果为 true,则执行 if 代码块,否则执行 else 代码块

流程图

C# if...else 语句

示例:使用 If-Else 语句

在此示例中,我们演示了 if-else 语句的用法 -

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

输出

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

a is not less than 20;
value of a is : 100

if...else if...else 语句

if 语句后可以跟一个可选的 else if...else 语句,这对于使用单个 if...else if 语句测试各种条件非常有用。

使用 if、else if、else 语句时,需要注意以下几点。

  • if 语句可以包含零个或一个 else,并且 else 必须位于任何 else if 语句之后。

  • if 语句可以包含零到多个 else if,并且 else 必须位于 else 语句之前。

  • 一旦 else if 语句成功执行,其余的 else if 或 else 语句将不再被测试。

语法

以下是 C# 中的 if...else if...else 语句−

if(boolean_expression 1) {
   /* 当布尔表达式 1 为真时执行 */
} 
else if( boolean_expression 2) {
   /* 当布尔表达式 2 为真时执行 */
} 
else if( boolean_expression 3) {
   /* 当布尔表达式 3 为真时执行 */
} else {
   /* 当以上条件都不成立时执行 */
}

示例:If、Else If、Else 的用法

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

using System;
namespace DecisionMaking {
   class Program {
      static void Main(string[] args) {
         /* 局部变量定义 */
         int a = 100;
         
         /* 检查布尔条件 */
         if (a == 10) {
            /* 如果条件为真,则打印以下内容 */
            Console.WriteLine("Value of a is 10");
         } 
         else if (a == 20) {
            /* if else if 条件为真 */
            Console.WriteLine("Value of a is 20");
         } 
         else if (a == 30) {
            /* if else if 条件为真  */
            Console.WriteLine("Value of a is 30");
         } else {
            /* 如果所有条件都不成立 */
            Console.WriteLine("None of the values is matching");
         }
         Console.WriteLine("Exact value of a is: {0}", a);
         Console.ReadLine();
      }
   }
}

输出

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

None of the values is matching
Exact value of a is: 100