Skip to content

C# - 嵌套If语句

在 C# 中,将 if 或 if-else 语句放置在另一个 if 或 else 块内部是完全有效的。这被称为嵌套(nesting)。嵌套 if 语句用于仅当主要条件为真时才测试次要条件。

嵌套 if 语句的基本语法如下:

if (primary_condition)
{
// 如果 primary_condition 为 true 则执行的代码
if (secondary_condition)
{
// 如果 primary_condition 和 secondary_condition 都为 true 则执行的代码
}
}

您还可以嵌套 if-else 和 else if 语句来处理更复杂的场景。

此示例检查一个数字是否为正数,如果是,则进一步检查它是否为偶数。

int number = 10;
// 主要条件:检查数字是否为正数
if (number > 0)
{
Console.WriteLine("The number is positive.");
// 嵌套条件:检查数字是否为偶数
if (number % 2 == 0)
{
Console.WriteLine("And it is also an even number.");
}
else
{
Console.WriteLine("And it is an odd number.");
}
}
else
{
Console.WriteLine("The number is not positive.");
}
// 输出:
// The number is positive.
// And it is also an even number.

在这里,我们使用嵌套逻辑来提供学生成绩的更详细反馈。

int marks = 85;
if (marks >= 90)
{
Console.WriteLine("Grade: A+");
}
else if (marks >= 80)
{
Console.WriteLine("Grade: A");
// 嵌套检查 A 级高分表现
if (marks >= 85)
{
Console.WriteLine("Excellent Performance!");
}
else
{
Console.WriteLine("Good Job!");
}
}
else if (marks >= 70)
{
Console.WriteLine("Grade: B");
}
else
{
Console.WriteLine("Grade: F - Needs Improvement");
}
// 输出:
// Grade: A
// Excellent Performance!

虽然嵌套 if 语句功能强大,但如果嵌套层级过深,它们会很快变得难以阅读和维护。这通常被称为**“箭头反模式”**(“Arrow Anti-pattern”),因为代码开始看起来像一个箭头 ->。

卫语句(Guard Clause)是方法开头的一个检查,如果条件不满足,则提前退出。这减少了嵌套,并将主要逻辑保持在顶级。

// --- 之前:嵌套 ---
public void ProcessOrder(Order order)
{
if (order != null)
{
if (order.IsVerified)
{
if (!order.IsShipped)
{
// 主要逻辑在这里...
Console.WriteLine("Processing the order...");
}
}
}
}
// --- 之后:使用卫语句 ---
public void ProcessOrder(Order order)
{
if (order == null) return;
if (!order.IsVerified) return;
if (order.IsShipped) return;
// 主要逻辑现在清晰且不再嵌套
Console.WriteLine("Processing the order...");
}

如果逻辑允许,您可以使用 &&(逻辑与)组合条件以扁平化结构。

// 而不是嵌套...
if (user.IsAuthenticated)
{
if (user.HasPermissions)
{
// ...
}
}
// 组合条件
if (user.IsAuthenticated && user.HasPermissions)
{
// ...
}

对于基于多个状态的复杂条件逻辑,switch 表达式比深度嵌套的 if-else 链更具可读性。

// 使用元组一次检查多个条件
string GetWeatherDescription(bool isRaining, int temperature)
{
return (isRaining, temperature) switch
{
(true, < 0) => "Freezing rain. Stay inside!",
(true, _) => "It's raining.",
(false, > 30) => "It's hot and sunny.",
(false, < 10) => "It's cold but dry.",
_ => "It's a pleasant day."
};
}
Console.WriteLine(GetWeatherDescription(true, -5)); // 输出:Freezing rain. Stay inside!
Console.WriteLine(GetWeatherDescription(false, 35)); // 输出:It's hot and sunny.