Dim a As Long = -9223372036854775808L
编译器将表达式-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
orl
appears as the token immediately following a unary minus operator token,the result is a constant of typelong
with the value -9223372036854775808 (-2^63). In all other situations,such a decimal_integer_literal is of typeulong
.