.net - vb.net - 为什么 ULong (UInt64) 不允许 += 运算符?

标签 .net vb.net

为什么我可以在创建时为 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 )不是 Int32UInt64 相比哪个范围太小.结果也可能是否定的,所以 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/

相关文章:

.net - 在 Windows Vista 中 reshape "glass"

c# - 是否所有 .NET 都已更新为使用 Contracts?

registry - 在键名包含空格的 VB.Net 中获取注册表键值

mysql - Visual Studio 2013 连接到本地 MySQL 数据库

asp.net - 将多个数据放入一个单元格 ASP.NET、VB.NET

javascript - Vb.net fileupload预览图像使用javascript

c# - 如何使用 LINQ to SQL 对分层数据进行查询?

.net - 是否可以独立于 BizTalk Server 使用 BizTalk 规则引擎?

c# - DataGridView AutoGenerateColumns以某种方式设置为true

.net - CaSTLe Windsor 子容器的快照