2011-07-15 144 views
2

這個看似簡單的代碼有什麼問題?三元運算符用法

invoice.GST > gstValue ? invoice.GST -= gstValue : invoice.GST = 0; 

VS抱怨
只有轉讓,電話,遞增,遞減和新對象表達式可以用作聲明

+3

三元操作就是這樣,運營商,而不是語句(如IF)。 – mletterle

+0

是的。我知道它是一個操作員,我在這個問題中寫了它,但我仍然把它當作一個聲明來處理!上帝救我... –

回答

6

試試這個:

invoice.GST = ((invoice.GST>gstValue)?(invoice.GST - gstValue):0); 
+0

這工作'invoice.GST =(invoice.GST> gstValue)? (invoice.GST - = gstValue):0;'感謝Cyber​​nate! –

+0

@Reddy:很高興幫助 – Chandu

+1

@Reddy:它的工作原理是因爲' - ='運算符返回被賦值的值。你可以把' - ='改成'-',它會有相同的效果(而且看起來不那麼奇怪)。 – cHao

3

因爲你不能使用invoice.GST > gstValue ? invoice.GST -= gstValue : invoice.GST = 0;作爲聲明(如VS告訴你的)。同樣喜歡你不能做到這一點:int i = 0; i;

你可以寫爲:invoice.GST = Math.Max(0, invoice.GST - gstValue);

1
invoice.GST = invoice.GST > gstValue ? invoice.GST - gstValue : 0; 

三元操作就像-+和其他運營商。

0

提到的表達式可以用作語句,因爲它們會導致副作用。

通常,沒有副作用的操作作爲語句沒有任何意義,因爲刪除操作符和僅評估操作數會產生相同的效果,這些通常表明行爲不是程序員所期望的。

例外情況是有條件評估操作數的三個操作符(其他兩個是&&||) - 消除操作符和操作數更改的副作用。在C和C++中,您有時會發現這些運算符僅用於進行條件評估,但C#不允許這樣做。在所有三種情況下,條件評估都可以使用if語句獲得,這也使得代碼更具可讀性。

0

試試這個:

invoice.GST -= invoice.GST > gstValue ? gstValue : invoice.GST;