C#嵌套if语句

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

语法

嵌套if语句的语法如下:

if( boolean_expression 1)
{
   /* Executes when the boolean expression 1 is true */
   if(boolean_expression 2)
   {
      /* Executes when the boolean expression 2 is true */
   }
}

可以使用与嵌套if语句相似的方式来嵌套else if...else语句。

示例

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

            /* check the boolean condition */
            if (a == 199)
            {
                /* if condition is true then check the following */
                if (b == 299)
                {
                    /* if condition is true then print the following */
                    Console.WriteLine("Value of a is 199 and b is 299");
                }
            }
            Console.WriteLine("Exact value of a is : {0}", a);
            Console.WriteLine("Exact value of b is : {0}", b);
            Console.ReadLine();
        }
    }
}

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

Value of a is 100 and b is 299
Exact value of a is : 199
Exact value of b is : 299

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