2014-02-27 97 views
7

我震驚知道有沒有算術運算符+-*/,並%在C#中8個和16位整數。我正在閱讀第23頁的「C#5.0 Pocket Reference」,如下所示。爲什麼C#中的8位和16位整數沒有算術運算符(+, - ,*,/,%)?

enter image description here

下面的代碼無法編譯。

class Program 
{ 
    static void With16Bit() 
    { 
     short a = 1; 
     short b = 2; 
     short c = a + b; 
     Console.WriteLine(c); 
    } 

    static void With8Bit() 
    { 
     byte a = 1; 
     byte b = 2; 
     byte c = a + b; 
     Console.WriteLine(c); 
    } 

    static void Main(string[] args) 
    { 
     With8Bit(); 
     With16Bit(); 
    } 
} 

爲什麼C#設計人員會這樣做?他們對此有何考慮?

+4

回答由埃裏克利珀http://stackoverflow.com/questions/941584/byte-byte-int-why/941627#comment750078_941584 – keyboardP

回答

9

算術與INT8的Int16;但結果是INT32,所以你必須

class Program 
{ 
    static void With16Bit() 
    { 
     short a = 1; 
     short b = 2; 
     short c = (short) (a + b); // <- cast, since short + short = int 
     Console.WriteLine(c); 
    } 

    static void With8Bit() 
    { 
     byte a = 1; 
     byte b = 2; 
     byte c = (byte) (a + b); // <- cast, since byte + byte = int 
     Console.WriteLine(c); 
    } 

    static void Main(string[] args) 
    { 
     With8Bit(); 
     With16Bit(); 
    } 
} 
+2

有此評論,但那是不是他的問題:「爲什麼C#設計人員這樣做?他們對此有何考慮?」 – Dirk

+0

這解釋了爲什麼不編譯,但沒有回答爲什麼設計者沒有爲字節,sbyte,shorts,ushort等操作符重載。 – keyboardP

+0

@keyboardP有**重載,這只是一個轉換錯誤。 – ken2k

5

普萊舍記住,當你在shortbyte進行加法運算的默認結果將是整數。

所以:

字節+字節= INT
短+短= INT

所以,如果你想找回你需要轉換回實際值。

試試這個:

 short a = 1; 
     short b = 2; 
     short c =(short) (a + b); 
     Console.WriteLine(c); 

     byte a = 1; 
     byte b = 2; 
     byte c =(byte) (a + b); 
     Console.WriteLine(c); 

Source

此行爲是因爲設計者沒有考慮到 byteshort爲實際數字,但他們認爲他們作爲 只序列號bits。所以對它們執行算術運算 沒有任何意義,所以如果是這樣的話int和long將爲 服務。

2

kek444 answer

All operations with integral numbers smaller than Int32 are widened to 32 bits 
before calculation by default. The reason why the result is Int32 is 
simply to leave it as it is after calculation. If you check the 
MSIL arithmetic opcodes, the only integral numeric type they operate 
with are Int32 and Int64. It's "by design".