为什么我可以在创建时为 ULong 分配一个文字值
Dim myULong As ULong = 0
但是在选项严格的情况下,我不能像下面那样递增?
myULong += 1
Visual Studio 2013 告诉我
Option Strict On disallows implicit conversions from 'Decimal' to 'ULong'.
我不知道 VS 如何在该行代码中得出小数...
感谢您的输入!
最佳答案
如果两个操作数的数据类型不同,则算术表达式的结果将是更精确的数据类型。
自 UInt64.MaxValue
大于 Int32.MaxValue
添加 UInt64
值到 Int32
值产生 Decimal
(参见: Widening and Narrowing Conversions )不是 Int32
与 UInt64
相比哪个范围太小.结果也可能是否定的,所以 UInt64
也不是一个好的选择。实际上没有来自 UInt64
的隐式转换到任何其他整数类型,甚至不是 Int64
( Long
) 因为它的范围更小。
这就是为什么尝试将结果重新分配给 UInt64
时会出现编译器错误的原因。值(value)。
你要么必须投它:
myULong = CULng(myULong + 1)
或(更好)使用
1UL
首先:myULong += 1UL
MSDN :
Type-unsafe conversions, cause a compiler error with Option Strict On. For example, if you try to add an Integer variable to a Double variable and assign the value to an Integer variable, a compiler error results, because a Double variable cannot be implicitly converted to type Integer.
顺便说一下,C# 会自动使用正确的类型,所以编译如下:
UInt64 myULong = 1;
myULong += 1; // here 1 is treated as UInt64
而这不会编译
myULong += -1; // -1 is Int32
关于.net - vb.net - 为什么 ULong (UInt64) 不允许 += 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25586898/