String 什么都不等于但也不等于什么。无法设置变量

String equals nothing but also does not equal nothing. Variable cannot be set

大范围的代码显示了 VB6 应用程序中的 .net 窗体。我遇到的小问题是为表单设置两个属性。此逻辑适用于另一种形式,但由于某种原因我无法在第二种形式上设置设备(输入参数 1)或扫描仪(输入参数 2)。

       'working case statement
       Case ScannerEdit
            Dim Device As String = String.Empty
            Dim Scanner As Integer = 0

            If formInputParameters IsNot Nothing AndAlso formInputParameters.Length >= 1 Then
                Device = formInputParameters(0)
            End If
            If formInputParameters IsNot Nothing AndAlso formInputParameters.Length >= 2 Then
                Scanner = formInputParameters(1)
            End If

            Dim f As frmScannerEdit = base
            f._Device = Device
            f._Scanner = Scanner

        'not working case statement
        Case ScannerCommandsList

            Dim Device As String = String.Empty
            Dim Scanner As Integer = 0

            If formInputParameters IsNot Nothing AndAlso formInputParameters.Length >= 1 Then
                Device = formInputParameters(0)
            End If
            If formInputParameters IsNot Nothing AndAlso formInputParameters.Length >= 2 Then
                Scanner = formInputParameters(1)
            End If

            Dim f As frmScannerCommandsList = base
            f._Device = Device
            f._Scanner = Scanner

虽然 运行 在调试中,代码创建了 Device 并将其设置为 Nothing,然后当参数集出现而不是将其设置为“TestDevice”时,它保持为空。与扫描仪相同。

我试过

If Device = Nothing Then
    Device = "TestDevice"
End If

在 set Device if 语句中,但它不认为这是真的;即使 Device = Nothing,该语句的结论也是错误的。为什么我不能设置一个变量,为什么当变量等于Nothing时变量不等于Nothing?

字符串变量Device不等于Nothing,初始化为String.Empty。那是不一样的。

尝试更改 If 语句以测试空字符串,例如

If Device.Length = 0 Then

If Device.Equals(String.Empty) Then

对于字符串,您可以使用 String.IsNullOrEmpty()String.IsNullOrWhitespace() 进行此类检查。

此外,可以创建一个包含实际元素的数组(该数组不是 Nothing 并且具有所需的长度),但仍然会为其中一个数组元素分配一个 Nothing 值。例如,给定这个数组 和问题 中完全相同的代码,Device 肯定会以 Nothing:

结束
Dim formInputParameters() As String = {Nothing, "0"}

If formInputParameters IsNot Nothing AndAlso formInputParameters.Length >= 1 Then
    Device = formInputParameters(0)
End If

最后,我看到 Scanner 被声明为一个整数,而 Device 是一个字符串,但两者都是从同一个数组(未知类型,因为我们不查看声明的位置)。 那不行! 这表明我你没有使用 Option Strict。现在已经不是 1997 年了。 Option Strict应该开启了!

当您设置此选项时,您会发现一堆新的编译器错误,并且很想将其关闭。不要那样做!这些错误中的每一个都是您的程序可能在 运行 时间失败的地方,而且它们几乎都可以轻松修复。花时间进行这些调整,您的程序将因此变得更加稳定和快速。

解决方法是更改​​第二个 case 语句中的变量名称,因为不知何故第一个语句声明了它们,却什么也没有。我假设这是一个 VB 怪癖。