C# 空合并 (??) 运算符的运算符优先级是什么?
- 作者: 今夜才发现耍猴的太多
- 来源: 51数据库
- 2022-10-20
问题描述
我刚刚尝试了以下方法,想法是连接两个字符串,用空字符串替换空字符串.
I've just tried the following, the idea being to concatenate the two strings, substituting an empty string for nulls.
string a="Hello"; string b=" World";
-- 调试(有趣的是?是打印,不完全有助于可读性...)
-- Debug (amusing that ? is print, doesn't exactly help readability...)
? a ?? "" + b ?? ""
->你好"
正确的是:
? (a??"")+(b??"") "Hello World"
我有点期待Hello World",或者如果 a 为空,则只是World".显然,这与运算符优先级有关,可以通过括号来解决,是否有任何地方可以记录此新运算符的优先级顺序.
I was kind of expecting "Hello World", or just "World" if a is null. Obviously this is todo with operator precedence and can be overcome by brackets, is there anywhere that documents the order of precedence for this new operator.
(意识到我可能应该使用 stringbuilder 或 String.Concat)
(Realising that I should probably be using stringbuilder or String.Concat)
谢谢.
推荐答案
除了您希望喜欢的优先级之外,ECMA 规定的是什么,MS 规定的是什么规范和 csc 实际做什么,我有一点建议:
Aside from what you'd like the precedence to be, what it is according to ECMA, what it is according to the MS spec and what csc actually does, I have one bit of advice:
不要这样做.
我认为写起来要清楚得多:
I think it's much clearer to write:
string c = (a ?? "") + (b ?? "");
或者,鉴于字符串连接中的 null 无论如何最终只是一个空字符串,只需写:
Alternatively, given that null in string concatenation ends up just being an empty string anyway, just write:
string c = a + b;
关于记录的优先级,在 C# 3.0 规范(Word 文档)和 ECMA-334,加法绑定比 ?? 更紧,后者比赋值绑定更紧.另一个答案中给出的 MSDN 链接是错误且奇怪的,IMO.2008 年 7 月的页面上显示的更改移动了条件运算符 - 但显然是错误的!
Regarding the documented precedence, in both the C# 3.0 spec (Word document) and ECMA-334, addition binds tighter than ??, which binds tighter than assignment. The MSDN link given in another answer is just wrong and bizarre, IMO. There's a change shown on the page made in July 2008 which moved the conditional operator - but apparently incorrectly!
- 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 包还原找不到包,没有源
