【发布时间】:2026-02-08 11:50:01
【问题描述】:
我知道在 C# 中使用 null coalescing operator 的标准方法是设置默认值。
string nobody = null;
string somebody = "Bob Saget";
string anybody = "";
anybody = nobody ?? "Mr. T"; // Returns Mr. T
anybody = somebody ?? "Mr. T"; // Returns "Bob Saget"
但是?? 还能用来做什么呢?它似乎没有ternary operator 有用,除了更简洁和更易于阅读之外:
nobody = null;
anybody = nobody == null ? "Bob Saget" : nobody; // Returns Bob Saget
所以考虑到甚至很少有人知道空合并运算符...
-
您是否将
??用于其他用途? -
??是必要的,还是应该只使用三元运算符(即 大多数人都熟悉)
【问题讨论】:
标签: c# coding-style null conditional-operator null-coalescing-operator