我正在见证.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 结果被提升为长期。

将其更改为:

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;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top