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

查看:139
本文介绍了什么是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 ?? ""



- >你好

-> "Hello"

正确的是:

? (a??"")+(b??"")
"Hello World"

我是那种期待的Hello 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 ?? "");



另外,考虑到空的字符串连接最终只是被一个空字符串无论如何,只写:

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链接是错误的和奇异的,海事组织。有一个在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天全站免登陆