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

前端之家收集整理的这篇文章主要介绍了.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.

猜你在找的VB相关文章