C# - 嵌套 if 语句
C# 中的嵌套 if 是另一个 if 语句的目标 if 语句。嵌套 if 语句在另一个 if 语句内部指定一个 if 或 if-else 语句。
在 C# 中,嵌套 if-else 语句始终是合法的,这意味着您可以在另一个 if 或 else if 语句内部使用一个 if 或 else if 语句。
语法
以下是 C# 嵌套 if 语句的语法 −
if( boolean_expression 1) {
/* 当 boolean_expression 1 为 true 时执行 */
if(boolean_expression 2) {
/* 当 boolean_expression 2 为 true 时执行 */
}
}
您可以以类似的方式嵌套 else if... else,就像您嵌套 if 语句一样。
示例:使用嵌套 If 语句
在以下示例中,我们演示了在 C# 程序中使用嵌套 if 语句 −
using System;
namespace DecisionMaking {
class Program {
static void Main(string[] args) {
//* 本地变量定义 */
int a = 100;
int b = 200;
/* 检查布尔条件 */
if (a == 100) {
/* 如果条件为 true,则检查以下内容 */
if (b == 200) {
/* 如果条件为 true,则打印以下内容 */
Console.WriteLine("Value of a is 100 and b is 200");
}
}
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 200 Exact value of a is : 100 Exact value of b is : 200
示例:嵌套 else-if 语句
在这个示例中,我们使用嵌套 else-if 语句以结构化的方式检查学生的成绩,具有多个条件 −
using System;
public class Example
{
public static void Main()
{
int marks = 85;
if (marks >= 90)
{
Console.WriteLine("Grade: A+");
}
else if (marks >= 80)
{
Console.WriteLine("Grade: A");
if (marks >= 85)
{
Console.WriteLine("Excellent Performance!");
}
else
{
Console.WriteLine("Good Job!");
}
}
else if (marks >= 70)
{
Console.WriteLine("Grade: B");
}
else if (marks >= 60)
{
Console.WriteLine("Grade: C");
}
else
{
Console.WriteLine("Grade: F - Needs Improvement");
}
}
}
输出
以下是上述代码的输出 −
Grade: A Excellent Performance!