2013-10-11 62 views
0

我只是想知道,如果下面的語法是合法的C#:我可以讓一個可爲空的變量爲負數嗎?

decimal price = -someVariable ?? 0M; 

基本上,我可以做一個可空變負,不知道,如果是空或不是?

+0

'小數價格= Math.Min((somevariable ?? 0M)* -1,(somevariable ' –

+0

此外,編譯器/測試一定會告訴你是或否:) –

回答

3

這可能不是因爲負號會附加到someVariable可能爲空,您可以將空合併包裝在括號中。

decimal price = -(someVariable ?? 0M); 
+0

是的,這正是我在流浪。謝謝。 – user1206480

+0

這是不正確的,就好像它是空的,你會以0m結束而不是空。 – Dave

2

是的,這是合法的,如果someVariable-someVariable也將。但爲了清楚起見,你可能要重寫爲以下幾點:

decimal price = -(someVariable ?? 0M); 

又如

decimal? a = null; 
decimal b = 5; 
decimal? c = a + b; // c == null 
相關問題