2011-03-02

C# byte相加及short相加竟然是int

今天做了將short相加的動作


ex.


short s1 = 1;


short s2 = 5;


short s3 = s1 + s2;             // 編譯不過


int s4 = s1+ s2;                 // ok


short s5 = (short)(s1 + s2); // ok




byte b1 = 1;


byte b2 = 2;


byte b3 = b1 + b2;             // 編譯不過


int b4 = b1+ b2;                 // ok


byte b5 = (byte)(b1 + b2);   // ok


 


原因是C# 會將 short 或 byte的四則運算轉置為int


所以相加之後 要記得做強行轉換


 


 


 


0 意見: