C# 提供了标准的控制流构造 — 条件语句(if、switch)、循环(、、)和分支语句(、、) — 以及现代增强特性,如 switch 表达式和模式匹配,使代码更简洁。
forforeachwhilebreakcontinuereturnif (score >= 90)
grade = "A";
else if (score >= 80)
grade = "B";
else
grade = "F";
// ternary and null-coalescing
string status = age >= 18 ? "adult" : "minor";
string name = input ?? "default"; // ?? — use default if input is null
name ??= "fallback"; // ??= assign if null
// traditional switch
switch (day)
{
case "Sat":
case "Sun":
type = "weekend";
break; // break required (no fall-through)
default:
type = "weekday";
break;
}
// switch EXPRESSION (C# 8) — concise, returns a value, with pattern matching
string type = day switch
{
"Sat" or "Sun" => "weekend",
_ => "weekday", // _ = default
};
// pattern matching in switch
string describe = obj switch
{
int n when n > 0 => "positive int",
string s => $"string of length {s.Length}",
null => "null",
_ => "other",
};
现代的 switch 表达式 简洁高效(返回值,无需 break),并支持强大的 模式匹配(匹配类型、条件等) — 相比冗长的传统 switch 语句,这是一个重大改进。
for (int i = 0; i < 10; i++) { }
foreach (var item in collection) { } // iterate any IEnumerable
while (condition) { }
do { } while (condition); // runs at least once
foreach(迭代任何 IEnumerable)是集合遍历的习惯用法。
foreach (var item in items)
{
if (item.Skip) continue; // next iteration
if (item.Stop) break; // exit loop
}
return result; // exit method
控制流是每个程序中表达逻辑的基本机制,因此理解 C# 的构造是日常基础知识。
虽然基础概念是标准的,但现代 C# 的增强特性值得了解和使用:switch 表达式(C# 8+)相比传统 switch 是一个重大改进 — 简洁、返回值、无落贯 bug(没有忘记的 break),并支持 模式匹配(匹配类型、条件、值和结构),这使复杂的条件逻辑远比嵌套 if-else 链清晰得多。
空合并运算符(??、??=)提供了简洁的空值处理,而 foreach 是遍历集合的习惯用法。
了解这些构造并倾向于使用现代、更具表现力的形式(使用模式匹配的 switch 表达式而非冗长的 switch 语句,使用空合并处理默认值)是编写简洁、习惯用法 C# 代码的日常知识。
switch 表达式和模式匹配尤其反映了现代 C# 向更函数式、更简洁代码的演进,因此理解它们对于编写更好的代码和阅读广泛使用这些特性的当前 C# 代码库都很重要。