C# 中的三元运算符和条件表达式

发布: (2026年2月19日 GMT+8 03:38)
6 分钟阅读
原文: Dev.to

I’m happy to help translate the text, but I need the actual content you’d like translated. Could you please paste the text (or the portion you want translated) here? I’ll keep the source line exactly as you provided and translate the rest into Simplified Chinese while preserving all formatting.

1. Conditional (Ternary) Operator ?:

语法

condition ? expressionIfTrue : expressionIfFalse;

示例

var status = isActive ? "Enabled" : "Disabled";

等价于

string status;
if (isActive)
    status = "Enabled";
else
    status = "Disabled";

何时使用

  • ✔ 当我们有 两个简单的选项
  • ✔ 当结果是 简单表达式
  • ✔ 当 提升可读性

何时避免

  • ❌ 当表达式 过大
  • ❌ 当包含 业务逻辑
  • ❌ 当 调试困难

📚 Microsoft Documentation

Conditional operator (?:)

2. 嵌套三元运算符

var grade =
    score >= 90 ? "A" :
    score >= 80 ? "B" :
    score >= 70 ? "C" :
    "Fail";

分析

允许在一个表达式中使用 多个条件,但 显著降低可读性

推荐

优先使用 switch 表达式 而不是嵌套三元运算符。

3. Null‑Conditional Operator ?.

避免 NullReferenceException

var name = user?.Name;

含义: 如果 user 不是 null,获取 Name,否则返回 null

等价于

var name = user != null ? user.Name : null;

何时使用

  • ✔ 当 读取嵌套属性
  • ✔ 当我们需要 null 安全访问

📚 Microsoft 文档

Member access operators (?., ?[])

4. Null‑Coalescing Operator ??

var name = input ?? "Default";

如果 inputnull → 返回 "Default"

等价于

var name = input != null ? input : "Default";

string name;
if (input == null)
    name = "Default";
else
    name = input;

📚 Microsoft Documentation

Null‑coalescing operator (??)

5. 空合并赋值 ??=

user.Name ??= "Guest";

仅在变量为 null 时才赋值。

  • a ?? b → 如果 a 不为 null 则返回 a,否则返回 b
  • a ??= b → 仅在 anull 时将 b 赋给 a

等价于

if (user.Name == null)
{
    user.Name = "Guest";
}

用途

  • 延迟初始化
  • 默认值
  • DTO 正规化

6. Throw Expressions (C# 7+)

我们可以在 expression 中使用 throw

var user = dto.User
    ?? throw new ArgumentNullException(nameof(dto.User));

var result = isValid
    ? value
    : throw new InvalidOperationException();

非常适合在构造函数或处理程序中使用 guard 子句

📚 Microsoft 文档

Throw expressions

7. 使用三元运算符的模式匹配

var name = obj is User u ? u.Name : "Unknown";

等价于

User u;
if (obj is User)
{
    u = (User)obj;   // cast
    name = u.Name;
}
else
{
    name = "Unknown";
}

if (obj is User u)
    return u.Name;

return "Unknown";

结合 type check + assignment。

  • ✔ 在 handlers 和 mapping logic 中非常有用。

📚 Microsoft Documentation

Pattern matching

8. Switch 表达式(现代替代)

var role = userType switch
{
    "Admin" => 10,
    "User"  => 5,
    _       => 0
};

解释:

  • 如果 userType"Admin"role = 10
  • 如果为 "User"role = 5
  • 对于任何其他值 (_) → role = 0

优势

  • ✔ 比嵌套三元运算更易读
  • ✔ 更适用于 多个条件
  • ✔ 支持 模式匹配

📚 Microsoft Documentation

Switch expressions

9 Advanced Pattern Matching (Property Patterns)

var message = user switch
{
    null => "No user",
    { IsActive: false } => "Inactive user",
    { Role: "Admin" } => "Welcome admin",
    _ => "Welcome"
};

这是一个针对 user 的 switch 表达式,根据其状态选择消息:

  • 如果 user == null"No user"
  • 否则如果 IsActive == false"Inactive user"
  • 否则如果 Role == "Admin""Welcome admin"
  • 否则 → "Welcome"

非常适用于 业务规则分类

何时使用条件表达式

  • 我们想要简短、清晰的赋值
  • 我们有简单的二元选择
  • 我们想要减少样板代码
  • 提高可读性

何时避免使用它们

  • 逻辑包含多个业务规则
  • 需要使用断点进行调试
  • 会产生嵌套的三元运算符
  • 可读性降低

最佳实践指南

  • 1 条件 → 三元运算符
  • 多个离散值 → switch 表达式
  • 空值回退??
  • 守卫子句?? throw
  • 复杂逻辑 → if/else 块

记住…

C# 中的条件表达式是创建表达性和简洁代码的强大工具。

  • 正确使用它们可以提升可读性并减少代码量。
  • 过度使用则会导致 “clever code” 而非 “clear code”。

原则: 先为人写代码,再为编译器写代码。

  • 当三元运算使代码更清晰时 — 使用它
  • 当它让代码更聪明但更难理解时 — 避免使用
0 浏览
Back to Blog

相关文章

阅读更多 »

OpenClaw 设计上不安全

OpenClaw 设计上不安全 Cline 供应链攻击 2月17日 一个流行的 VS Code 扩展 Cline 被攻破。攻击链展示了多个 AI …

EDuke32 – Duke Nukem 3D(开源)

是时候大干一场、嚼口香糖了,我的口香糖已经用完! Polymer renderer screenshot/images/shots/polymer2.jpg 每像素动态光照和实时阴影……