C# 空合并 (??) 运算符的运算符优先级是什么?

What is the operator precedence of C# null-coalescing (??) operator?(C# 空合并 (??) 运算符的运算符优先级是什么?)
本文介绍了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# 空合并 (??) 运算符的运算符优先级是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

ActiveDirectory error 0x8000500c when traversing properties(遍历属性时 ActiveDirectory 错误 0x8000500c)
search by samaccountname with wildcards(使用通配符按 samaccountname 搜索)
Get the list of Groups for the given UserPrincipal(获取给定 UserPrincipal 的组列表)
Can you find an Active Directory User#39;s Primary Group in C#?(你能在 C# 中找到 Active Directory 用户的主要组吗?)
Query From LDAP for User Groups(从 LDAP 查询用户组)
How can I get DOMAINUSER from an AD DirectoryEntry?(如何从 AD DirectoryEntry 获取 DOMAINUSER?)