Skip to content

C# - If语句

if 语句是编程中一种基本的控制流结构。它允许你的代码进行决策,并仅在给定条件为 true 时执行特定的代码块。

if 语句的语法非常直接:

if (boolean_expression)
{
// 如果 boolean_expression 为 true,则执行此代码块。
}

boolean_expression 必须评估为 true 或 false。如果为 true,则执行花括号 {} 内的代码。如果为 false,则跳过该代码块,程序继续执行 if 块之后的下一条语句。

你可以这样可视化 if 语句的流程:

( 开始 )
|
v
+---------------------+
| 条件为真吗? | -- 否 --> ( 跳过代码块并继续 )
+---------------------+
|
是
|
v
+---------------------+
| 执行 'if' 代码块 |
| 中的代码 |
+---------------------+
|
v
( 在代码块后继续 )

这是一个简单的例子,检查学生的成绩是否及格。

// 现代 C# 的顶级语句
int score = 85;
int passingScore = 60;
Console.WriteLine($"Your score is: {score}");
if (score >= passingScore)
{
Console.WriteLine("Congratulations, you passed!");
}
// 无论条件是否满足,这行代码都会执行
Console.WriteLine("Finished checking score.");

当上述代码编译并执行时,会产生:

Your score is: 85
Congratulations, you passed!
Finished checking score.

if 语句的一个常见用途是处理集合中的项,并仅对符合特定条件的项执行操作。在此示例中,我们筛选产品列表,只显示正在促销的产品。

using System;
using System.Collections.Generic;
// 一个表示产品的简单 record 类型
public record Product(string Name, decimal Price, bool IsOnSale);
var products = new List<Product>
{
new Product("Laptop", 1200m, false),
new Product("Mouse", 25m, true),
new Product("Keyboard", 75m, true),
new Product("Monitor", 300m, false)
};
Console.WriteLine("--- Products On Sale ---");
foreach (var product in products)
{
// 使用 if 语句检查 IsOnSale 属性
if (product.IsOnSale)
{
Console.WriteLine($"- {product.Name} is available for just ${product.Price}!");
}
}

输出将只包含 IsOnSale 为 true 的产品:

--- Products On Sale ---
- Mouse is available for just $25!
- Keyboard is available for just $75!

1. 始终使用花括号 {}: 即使你的 if 块只包含一行代码,始终使用花括号也是被广泛接受的最佳实践。这可以提高可读性,并防止你在以后向该块添加更多行时引入错误。

// 良好实践:清晰且安全
if (condition)
{
DoSomething();
}
// 不良实践:可能导致错误
if (condition)
DoSomething();
DoSomethingElse(); // 这行代码不是 if 语句的一部分!

2. 与 else 和 else if 结合使用: if 语句通常与 else(在条件为 false 时执行代码)和 else if(按顺序检查多个条件)配对使用。这些允许你构建更复杂的决策逻辑。

3. 保持条件简单: 如果你的布尔表达式变得非常长和复杂,请考虑将其重构为一个单独的布尔变量或方法。这使得你的 if 语句更易于阅读。

bool canUserAccessFile = user.IsAuthenticated && (user.HasReadPermission || user.IsAdmin); if (canUserAccessFile) { ... }