为什么当变量在长数据类型范围内时编译器会报错

Why compiler is complaining while variable is in the range of long data type

我在 class 中有以下声明。

public class MyClass
{
    private const long SOME_VALUE= (10 * 1024 * 1024 * 1024);  // 10 GB
    ....
}

但是编译器报告以下错误

error CS0220: The operation overflows at compile time in checked mode

根据MSDN

据我所知,SOME_VALUElong 类型的范围内。关于为什么我会收到此编译时错误的任何想法?

计算中的每个单独值都是 int,因此编译器将它们相乘为 int,因此会溢出。最简单的解决方案是使用 L suffix 将它们中的一个或全部标记为 long,这将强制计算为 long:

private const long SOME_VALUE= 10L * 1024 * 1024 * 1024;

添加L后缀:

public class MyClass
{
    private const long SOME_VALUE= (10L * 1024L * 1024L * 1024L);  // 10 GB
    ....
}

没有 L 后缀(代表 long)编译器将表达式视为 int 之一并警告整数溢出。