【问题标题】:Why compiler is complaining while variable is in the range of long data type为什么编译器在变量在长数据类型范围内时抱怨
【发布时间】:2017-02-27 02:43:35
【问题描述】:
我在课堂上有以下声明。
public class MyClass
{
private const long SOME_VALUE= (10 * 1024 * 1024 * 1024); // 10 GB
....
}
但是编译器报告以下错误
错误 CS0220:在检查模式下编译时操作溢出
根据MSDN.
据我所知,SOME_VALUE 在 long 类型的范围内。关于为什么会出现此编译时错误的任何想法?
【问题讨论】:
标签:
c#
types
compiler-errors
long-integer
【解决方案1】:
计算中的每个单独的值都是int,因此编译器将它们相乘为ints,因此溢出。最简单的解决方案是使用L suffix 将其中一个或全部标记为long,这将强制计算为long:
private const long SOME_VALUE= 10L * 1024 * 1024 * 1024;
【解决方案2】:
添加L后缀:
public class MyClass
{
private const long SOME_VALUE= (10L * 1024L * 1024L * 1024L); // 10 GB
....
}
没有L 后缀(代表long)编译器将表达式视为int 1 并警告整数溢出。