此 C# 语句的 VB.NET 版本是否需要 unchecked 关键字?

Is the unchecked keyword necessary in the VB.NET version of this C# statement?

我正在转换为 VB.NET,它不提供 unchecked 关键字。但在这个声明中似乎没有必要:

const int dwAccess = unchecked((int)0xC0000000);

我在这里有两个观察结果:

  1. dwAccess 声明为常量
  2. 分配的值正好在System.Int32
  3. 的范围内

考虑到这些,是否安全:

Const dwAccess As Integer = &HC0000000

在这种情况下使用它:

[DllImport("Kernel32", CharSet = CharSet.Auto, SetLastError = true)]
private static extern SafeFileHandle CreateFile(string lpFileName, int dwAccess, int dwShareMode,
                                                IntPtr securityAttrs, int dwCreationDisposition,
                                                int dwFlagsAndAttributes, IntPtr hTemplateFile);

澄清:这个问题不是关于unchecked关键字在C#中是否必要的问题。 显然是。是关于VB.NET中没有关键字是否排除语句转换成功的问题。

答案是肯定的。它是多余的,可以删除。

unchecked (C# Reference)

The unchecked keyword is used to suppress overflow-checking for integral-type arithmetic operations and conversions.


更新,这个回答应该是合格的。

如果原始 VB.NET 代码未选中,则等效的 C# 代码也将以相同的方式运行,就像未选中一样。两者都会溢出,并且都会给出相同的结果。

是的。以下是可以的:

Const dwAccess As Integer = &HC0000000

VB.Net中没有unchecked关键字,但是有一个编译标志-removeintchecks1会导致整个程序不检查整数溢出.

如果C#行是:

const int dwAccess = unchecked((int)0xC0000000);

那么 VB.Net 翻译将如下所示:

Const dwAccess As Integer = &HC0000000

由于0xC0000000uint范围内,但不在int范围内,所以在C#中使用unchecked关键字将值转换为int 格式。在 VB.Net 中,十六进制常量的转换是自动的。