C#巢狀if語句

2019-10-16 23:17:21

在 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