您需要注意 0、Nothing 和 vbNull 之间的区别。
0 是布尔值的默认值。
vbNull 是保留的 Null 值,应转换为 1。
几乎在所有情况下都不会引发异常。
Dim a As Boolean? = Nothing
Dim b As Boolean? = vbNull
Dim c As Boolean = vbNull
Dim d As Boolean
Print(a = True) 'will throw an Exception
Print(b = True) 'will return True (as vbNull = Int(1))
Print(c = True) 'will return True as the ? is unnecessary on a Boolean as vbNull = Int(1)
Print(d = True) 'will return False as the default value of a Boolean is 0
Print(a.GetValueOrDefault) 'will return False as this handles the Nothing case.
在使用未分配的值时,您应该始终首先检查 Nothing(或者只是遵循良好做法并在使用之前设置值)。
Dim a As Boolean?
Dim b As Boolean = IIf(IsNothing(a), False, a)
如果 a 为 Nothing,则返回 False,否则返回 A。
只有在测试 Nothing 之后才能测试 vbNull,因为 Nothing 在所有值上都会返回错误。下面的代码将在 Nothing 或 vbNull 或其他情况下返回 False。
Dim a As Boolean?
Dim b As Boolean = IIf(IsNothing(a), False, IIf(a = vbNull, False, a))
注意:您不能使用下面的代码,因为测试 a = vbNull 将反对 Nothing ,这将引发异常。
Or(IsNothing(a), a = vbNull)
我也会避免在任何实际应用程序中使用 GetValueOrDefault,因为当您开始使用更复杂的数据类型时,默认值不会那么简单,而且您会得到意想不到的结果。恕我直言,测试 IsNothing(或 Object = Nothing,Object Is Nothing)比依赖数据类型的怪癖好得多。
最佳做法是确保 a 具有价值,您可以使用
Dim a As Boolean? = New Boolean()
Dim b As Boolean = a
我之所以说这是最佳实践,是因为它可以转换为所有类,而不仅仅是布尔值。注意到这对于布尔值来说是多余的。
希望这会有所帮助。