Dot-Net
為什麼我的 .net Int64 的行為就像 Int32 一樣?
我在 .net 程序中目睹了一種奇怪的行為:
Console.WriteLine(Int64.MaxValue.ToString()); // displays 9223372036854775807, which is 2^63-1, as expected Int64 a = 256*256*256*127; // ok Int64 a = 256*256*256*128; // compile time error : //"The operation overflows at compile time in checked mode" // If i do this at runtime, I get some negative values, so the overflow indeed happens.為什麼我的 Int64 的行為就好像它們是 Int32 的一樣,儘管 Int64.MaxValue 似乎確認它們使用的是 64 位?
如果相關,我使用的是 32 位作業系統,並且目標平台設置為“任何 CPU”
您的 RHS 僅使用
Int32值,因此整個操作使用Int32算術執行,然後將Int32結果提升為 long。將其更改為:
Int64 a = 256*256*256*128L;一切都會好起來的。
利用:
Int64 a = 256L*256L*256L*128L;L 後綴表示 Int64 字面量,無後綴表示 Int32。
你寫的:
Int64 a = 256*256*256*128方法:
Int64 a = (Int32)256*(Int32)256*(Int32)256*(Int32)128;