2010-07-15 128 views
20

最近我有一個奇怪的錯誤,我在連接字符串與int?,然後加入之後另一個字符串。奇怪的運算符優先級與?? (空合併運算符)

我的代碼基本上是這樣的等價物:

int? x=10; 
string s = "foo" + x ?? 0 + "bar"; 

令人吃驚的是,這將運行並沒有出現警告或不兼容的類型錯誤編譯,也將這樣的:

int? x=10; 
string s = "foo" + x ?? "0" + "bar"; 

然後這導致意外類型不兼容性錯誤:

int? x=10; 
string s = "foo" + x ?? 0 + 12; 

就像這樣簡單例如:

int? x=10; 
string s = "foo" + x ?? 0; 

有人可以解釋這是如何對我有用嗎?

+0

一個相關的問題:http://stackoverflow.com/questions/3218140/null-coalescing-operator-and-lambda-expression/3218268#3218268 – 2010-07-15 21:38:23

+0

這裏是一個鏈接,不會使我的答案發光... http://stackoverflow.com/questions/3218140/null-coalescing-operator-and-lambda-expression – ChaosPandion 2010-07-15 22:17:18

回答

25

空合併操作具有非常低的precedence因此您的代碼被解釋爲:

int? x = 10; 
string s = ("foo" + x) ?? (0 + "bar"); 

在這個例子中兩個表達式都是字符串,因此編譯,但你想要的東西沒有做。在你的下一個例子中,??運營商的左側是一個字符串,而右手邊是一個整數,所以它不會編譯:

int? x = 10; 
string s = ("foo" + x) ?? (0 + 12); 
// Error: Operator '??' cannot be applied to operands of type 'string' and 'int' 

當然解決的辦法是加括號:

int? x = 10; 
string s = "foo" + (x ?? 0) + "bar"; 
+0

阿所以由於低優先級的兩側形成幾乎兩個單獨的表達式 – Earlz 2010-07-15 19:49:56

+0

這解釋了爲什麼'INT X = 10;字符串s =「foo」+ x ?? 「0」;'作品然後 – Earlz 2010-07-15 20:00:44

10

??操作符比+運營商降低precedence,讓你的表情真的作品爲:

string s = ("foo" + x) ?? (0 + "bar"); 

杉木第一字符串"foo"x字符串值被連接,並且如果這將是空(它不能是),的0字符串值和字符串"bar"是級聯。

+3

照片完成:) 1秒勝利:) – 2010-07-15 19:50:36