在 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