在 C# 中巢狀if-else
語句總是合法的,這意味著您可以在一個if
或else
語句中使用另一個if
或else 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