問題描述
我剛剛嘗試了以下方法,想法是連接兩個字符串,用空字符串替換空字符串.
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# 空合并 (??) 運算符的運算符優先級是什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!