C# if-else语句

一个if语句可以跟随一个可选的else语句,当布尔表达式为false时,则将执行else块中的代码。

语法

C# 中if...else语句的语法是:

if(boolean_expression)
{
   /* statement(s) will execute if the boolean expression is true */
}else
{
   /* statement(s) will execute if the boolean expression is false */
}

如果布尔表达式(boolean_expression)的值为true,则执行if代码块,否则执行else代码块。

流程图

示例代码

using System;
namespace DecisionMaking
{
   class Program 
   {
      static void Main(string[] args)
      {
         /* local variable definition */
         int a = 199;

         /* check the boolean condition */
         if (a < 10)
         {
            /* if condition is true then print the following */
            Console.WriteLine("a is less than 10");
         }
         else
         {
            /* if condition is false then print the following */
            Console.WriteLine("a is not less than 10");
         }
         Console.WriteLine("value of a is : {0}", a);
         Console.ReadLine();
      }
   }
}

当编译和执行上述代码时,会产生以下结果:

a is not less than 19;
value of a is : 199

if…else if…else语句

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

当使用ifelse if, else语句时要注意以下几点 -

  • 一个if语句可以有零个或一个else语句,但它必须放在else if语句之后。
  • 一个if语句可以有零到多个else if语句,但必须放在else语句之前。
  • 一旦有一个else if条件测试成功,剩下的其他if elseelse将不会再被测试。

语法

C# 中if...else if...else语句的语法是:

if(boolean_expression 1)
{
   /* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
   /* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
   /* Executes when the boolean expression 3 is true */
}
else 
{
   /* executes when the none of the above condition is true */
}

示例

using System;
namespace DecisionMaking
{
    class Program
    {
        static void Main(string[] args)
        {
            /* local variable definition */
            int a = 199;

            /* check the boolean condition */
            if (a == 19)
            {
                /* if condition is true then print the following */
                Console.WriteLine("Value of a is 19");
            }
            else if (a == 29)
            {
                /* if else if condition is true */
                Console.WriteLine("Value of a is 29");
            }
            else if (a == 39)
            {
                /* if else if condition is true  */
                Console.WriteLine("Value of a is 39");
            }
            else
            {
                /* if none of the conditions is true */
                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: 199

上一篇: C#决策结构 下一篇: C#循环