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#迴圈