.net – “溢出”编译器错误-9223372036854775808L

Long data type的范围是-9223372036854775808到9223372036854775807,但以下语句生成编译器错误“BC30036:溢出”:
Dim a As Long = -9223372036854775808L

Try it online!

为什么这是一个错误?如何在代码中指定常量-9223372036854775808?

为什么这是一个错误

编译器将表达式-9223372036854775808L解析为应用于十进制整数文字9223372036854775808L的一元减号运算符.根据VB.NET specification

A decimal integer literal is a string of decimal digits (0-9).

和:

If an integer literal’s type is of insufficient size to hold the integer literal,a compile-time error results.

9223372036854775808L对于Long而言太大,因此会出现溢出错误.
(减号不是整数文字的一部分.)

如何在代码中指定常量-9223372036854775808?

要按字面指定-9223372036854775808,请使用十六进制文字

Dim a As Long = &H8000000000000000

VB.NET规范也提到了这一点:

Decimal literals directly represent the decimal value of the integral literal,whereas octal and hexadecimal literals represent the binary value of the integer literal (thus,&H8000S is -32768,not an overflow error).

当然,为了清楚起见,您应该只使用Long.MinValue而不是文字

Dim a As Long = Long.MinValue

C#怎么样?

正如RenéVogt指出的那样,等效语句在C#中编译得很好:

long a = -9223372036854775808L;

那是因为(与VB.NET不同)C# supports this as a special case

When a decimal_integer_literal with the value 9223372036854775808 (2^63) and no integer_type_suffix or the integer_type_suffix L or l appears as the token immediately following a unary minus operator token,the result is a constant of type long with the value -9223372036854775808 (-2^63). In all other situations,such a decimal_integer_literal is of type ulong.

相关文章

Format[$] ( expr [ , fmt ] ) format 返回变体型 format$ 强...
VB6或者ASP 格式化时间为 MM/dd/yyyy 格式,竟然没有好的办...
在项目中添加如下代码:新建窗口来显示异常信息。 Namespace...
转了这一篇文章,原来一直想用C#做k3的插件开发,vb没有C#用...
Sub 分列() ‘以空格为分隔符,连续空格只算1个。对所选...
  窗体代码 1 Private Sub Text1_OLEDragDrop(Data As Dat...