2012-03-23 110 views
1

我發現在C#中a + = 1不等於a = a + 1。C#中a + = 1和a = a + 1的區別

例如,以下代碼編譯時沒有任何錯誤: byte b = 10; b + = 5;

while while following code has a compilation error: byte b = 10; b = b + 5;

有人可以讓我知道爲什麼嗎?

+0

錯誤消息始終有幫助 – 2012-03-23 04:43:47

+0

錯誤消息是:「不能將類型'int'隱式轉換爲'byte'。存在明確的轉換(您是否缺少轉換?)」 – Morteza 2012-03-23 04:47:11

+0

請參見:http:// stackoverflow。 COM /問題/ 4343624 /整數加法布魯斯 - 短 - 短 - 問題 – 2012-03-23 04:47:30

回答

7

因爲b + 5成爲一個整數(的Int32)(主要是因爲有過載的可能性)

和下面的化合物分配規範規定:

Otherwise, if the selected operator is a predefined operator, if the return type of the selected operator is explicitly convertible to the type of x, and if y is implicitly convertible to the type of x or the operator is a shift operator, then the operation is evaluated as x = (T)(x op y), where T is the type of x, except that x is evaluated only once.

0

編譯器可能是治療5作爲一個Int32在第二個。你需要投它

1

因爲b += 5編譯好像它讀取b = (byte)(b + 5)。演員負責轉換到正確的類型,所以沒有錯誤。

相關問題