C# 空合并 (??) 运算符的运算符优先级是什么? [英] What is the operator precedence of C# null-coalescing (??) operator?

查看:35
本文介绍了C# 空合并 (??) 运算符的运算符优先级是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚尝试了以下方法,想法是连接两个字符串,用空字符串替换空字符串.

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# 空合并 (??) 运算符的运算符优先级是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆