UInt64和"在检查模式下编译时操作溢出" - CS0220

Rob*_*der 13 c# math logic uint64

这感觉就像一个愚蠢的问题,但我似乎无法看到答案.我有一个UInt64,它的最大值应该是

UInt64.MaxValue 18446744073709551615
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试分配一个中等大小的数字时,我得到"溢出错误""在检查模式下编译时操作溢出".如果我将它包装在"未经检查"的块中,那么它将编译,并运行,就像此变量为零一样:

UInt64 value1 = 1073741824 * 8; // Compile error CS0220
UInt64 value2 = 8589934592;     // Actual value - no error
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

vcs*_*nes 25

因为:

UInt64 value1 = 1073741824 * 8;
Run Code Online (Sandbox Code Playgroud)

是将算术作为带符号的32位整数,然后将其转换为ulong.尝试:

UInt64 value1 = 1073741824UL * 8;
Run Code Online (Sandbox Code Playgroud)

UL意味着文字是无符号长的.有关字面后缀的更多信息,请参阅C#规范的2.4.4节:

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