Skip to content

C# - If Else语句

条件语句允许您的程序根据指定条件执行不同的代码块。if-else 语句是 C# 中最基本的控制流结构,用于做出决策。

if 语句仅在其布尔条件评估为 true 时执行一个代码块。

int userAge = 20;
if (userAge >= 18)
{
Console.WriteLine("Access granted. You are an adult.");
}
// Output: Access granted. You are an adult.

您可以添加 else 块,在 if 条件为 false 时提供另一种执行路径。

if (boolean_expression)
{
// Executes if the expression is true
}
else
{
// Executes if the expression is false
}

控制流可以可视化为道路上的一个分岔口:

( Condition? )
/ \
true / \ false
/ \
(if block) (else block)
int temperature = 15;
if (temperature > 25)
{
Console.WriteLine("It's a hot day. Wear shorts!");
}
else
{
Console.WriteLine("It's cool outside. Consider a jacket.");
}
// Output: It's cool outside. Consider a jacket.

要按顺序测试多个条件,您可以链接 else if 语句。一旦满足一个条件,其代码块就会执行,并且链的其余部分将被跳过。

int score = 85;
if (score >= 90)
{
Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
Console.WriteLine("Grade: B"); // This block will be executed
}
else if (score >= 70)
{
Console.WriteLine("Grade: C");
}
else
{
Console.WriteLine("Grade: F");
}
// Output: Grade: B

对于简单的 if-else 赋值,三元运算符提供了高度简洁的语法。它是一个返回值的表达式。

int userAge = 20;
// Syntax: condition ? value_if_true : value_if_false;
string status = (userAge >= 18) ? "Adult" : "Minor";
Console.WriteLine($"User status: {status}"); // Output: User status: Adult

对于评估单个变量的复杂 if-else if 链,switch 表达式通常更具可读性且更不容易出错。

int statusCode = 404;
string message = statusCode switch
{
200 => "OK",
401 => "Unauthorized",
404 => "Not Found",
500 => "Internal Server Error",
_ => "Unknown Status Code" // The discard '_' acts as the default case
};
Console.WriteLine($"Response: {message}"); // Output: Response: Not Found
  • 使用大括号 {}:始终为 if 和 else 块使用大括号,即使是单行语句。这可以防止以后添加更多行时引入 bug。
  • 避免深度嵌套:深度嵌套的 if 语句(箭头代码)难以阅读。使用方法、switch 语句或守卫子句(guard clauses)对其进行重构。
  • 守卫子句:在方法开始时检查无效条件并提前退出。这可以扁平化您的逻辑。
  • 短路求值(Short-Circuiting):请注意,逻辑与(&&)和逻辑或(||)运算符是“短路求值”的。在 A && B 中,如果 A 为假,则 B 不会被评估。这对于防止错误很有用,例如 if (user != null && user.IsAdmin)。
  • 常见错误:在条件中使用赋值运算符(=)而不是相等运算符(==)。C# 通过要求 if 条件为 bool 类型来帮助防止此错误,但这是一个需要注意的经典 bug。