少于 1 分钟阅读 次阅读

在处理可能为 null 的值时,我们经常需要提供回退值或默认值。C# 中的空合并运算符 ?? 专门为此设计,它提供了一种简洁、表达力强的方式来处理空值情况,避免了冗长的三元运算符或 if 语句。

1 基础语法

空合并运算符 ?? 的基本语法是:左表达式 ?? 右表达式

string displayName = name ?? "匿名用户";

2 工作原理

a ?? b 的求值规则很简单:

  1. 计算左侧表达式 a 的值
  2. 如果 a 不为 null,返回 a 的值
  3. 如果 anull,计算并返回右侧表达式 b 的值

3 常见用法场景

3.1 提供默认值

// 为可能为null的字符串提供默认值
string greeting = userPreference?.GreetingMessage ?? "欢迎!";

// 为数值类型提供默认值
int maxRetries = configuration?.MaxRetryCount ?? 3;

3.2 简化空值检查

// 传统方式
string connectionString;
if (configuration.ConnectionString != null)
{
    connectionString = configuration.ConnectionString;
}
else
{
    connectionString = GetDefaultConnectionString();
}

// 使用 ?? 运算符
string connectionString = configuration.ConnectionString ?? GetDefaultConnectionString();

3.3 与可空值类型配合

?? 运算符特别适合处理可空值类型:

int? nullableId = GetIdFromDatabase();
int actualId = nullableId ?? -1; // 如果数据库返回null,使用-1

// 对于布尔值
bool? userConsent = GetUserConsent();
bool canProceed = userConsent ?? false;

3.4 短路求值

?. 类似,?? 也支持短路求值。如果左侧不为 null,右侧表达式根本不会计算

// 如果data不为null,ExpensiveOperation()不会被调用
var result = data ?? ExpensiveOperation();

3.5 联合使用示例

// 经典组合:安全访问 + 默认值
string userName = user?.Profile?.Name ?? "匿名用户";
int score = player?.Statistics?.HighScore ?? 0;
List<string> items = order?.LineItems?.ToList() ?? new List<string>();

4 优先级

?? 的优先级较低,在复杂表达式中可能需要括号:

// 可能需要括号来明确意图
var x = a + b ?? c;    // 错误:+ 的优先级高于 ??
var x = (a + b) ?? c;  // 正确

标签:

分类:

更新时间:

留下评论