Unique ways to use the null coalescing operator(使用空合并运算符的独特方法)
问题描述
我知道在 C# 中使用 null 合并运算符的标准方法是设置默认值值.
I know the standard way of using the null coalescing operator in C# is to set default values.
string nobody = null;
string somebody = "Bob Saget";
string anybody = "";
anybody = nobody ?? "Mr. T"; // Returns Mr. T
anybody = somebody ?? "Mr. T"; // Returns "Bob Saget"
但是??还能用来做什么?除了更简洁和更容易阅读:
But what else can ?? be used for? It doesn't seem as useful as the ternary operator, apart from being more concise and easier to read than:
nobody = null;
anybody = nobody == null ? "Bob Saget" : nobody; // Returns Bob Saget
因此,很少有人知道空合并运算符...
So given that fewer even know about null coalescing operator...
您是否将
??用于其他用途?
?? 是必需的,还是应该使用三元运算符(即大多数都熟悉)
Is ?? necessary, or should you just use the ternary operator (that
most are familiar with)
推荐答案
嗯,首先,它比标准的三元运算符更容易链接:
Well, first of all, it's much easier to chain than the standard ternary operator:
string anybody = parm1 ?? localDefault ?? globalDefault;
对比
string anyboby = (parm1 != null) ? parm1
: ((localDefault != null) ? localDefault
: globalDefault);
如果可能为 null 的对象不是变量,它也能很好地工作:
It also works well if a null-possible object isn't a variable:
string anybody = Parameters["Name"]
?? Settings["Name"]
?? GlobalSetting["Name"];
对比
string anybody = (Parameters["Name"] != null ? Parameters["Name"]
: (Settings["Name"] != null) ? Settings["Name"]
: GlobalSetting["Name"];
这篇关于使用空合并运算符的独特方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用空合并运算符的独特方法
基础教程推荐
- 从 C# 控制相机设备 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 将数据集转换为列表 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 如果条件可以为空 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
