UInt64和“操作在编译时在检查模式下溢出". -CS0220 [英] UInt64 and "The operation overflows at compile time in checked mode" - CS0220

查看:402
本文介绍了UInt64和“操作在编译时在检查模式下溢出". -CS0220的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个愚蠢的问题,但我似乎看不到答案.我有一个UInt64,应该具有

This feels like a stupid question, but I can't seem to see the answer. I have an UInt64, which is supposed to have a max value of

UInt64.MaxValue 18446744073709551615

但是,当我尝试分配一个大小适中的数字时,出现此溢出错误操作在检查模式下在编译时溢出".如果我将其包装在"unchecked"块中,则它将编译并像该变量为零一样运行:

However, when I try to assign a modest-sized number, I get this overflow error of "The operation overflows at compile time in checked mode". If I wrap it in an "unchecked" block then it compiles, and runs as if this variable is zero:

UInt64 value1 = 1073741824 * 8; // Compile error CS0220
UInt64 value2 = 8589934592;     // Actual value - no error

为什么会这样?

推荐答案

原因:

UInt64 value1 = 1073741824 * 8;

将算术运算为有符号的32位整数,然后然后将其转换为ulong.试试:

Is doing the arithmetic as a signed 32-bit integer, then converting it to an ulong. Try:

UInt64 value1 = 1073741824UL * 8;

UL表示文字是无符号长整数.有关文字后缀的更多信息,请参见C#规范的2.4.4节:

The UL means that the literal is of an unsigned long. See section 2.4.4 of the C# Specification for more on literal suffixes:

如果文字后缀为UL,Ul,uL,ul,LU,Lu,lU或lu,则其类型为ulong

If the literal is suffixed by UL, Ul, uL, ul, LU, Lu, lU, or lu, it is of type ulong

这篇关于UInt64和“操作在编译时在检查模式下溢出". -CS0220的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆