使用空合并运算符的独特方法
- 作者: 首席鉴穴师
- 来源: 51数据库
- 2022-10-20
问题描述
我知道在 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#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
热点文章
团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
0
使用 MSBuild.exe 在发布模式下构建 C# 解决方案
0
当我发布 Web 应用程序时,AfterPublish 脚本不运行
0
构建时 T4 转换的产品仅在下一个构建中使用
0
ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
0
新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
0
如何将条件编译符号(DefineConstants)传递给 msbuild
0
MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
0
NuGet 包还原找不到包,没有源
0
使用 C# 6.0 功能运行 TFS 构建
0
