如何影响布尔值布尔值的结果?表达



我想在VB中编写与C#中相同的代码:

bool? a = whatever;
bool b= (a==true);

VB编译器不接受这个:

Dim a As Boolean?
Dim b As Boolean = (a = True)

我想在这种情况下,它将(a = True)解释为一种做作,而我希望它被解释为一个表达。(a == True)显然是一个语法错误。

您可以使用GetValueOrDefault-方法:

Dim a As Boolean?
Dim b As Boolean = a.GetValueOrDefault()

您也可以使用CBool

Dim a As Boolean?
Dim b As Boolean = CBool(a = True)

您需要小心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,因为当你开始使用更复杂的数据类型时,默认值不会那么简单,你可能会得到意想不到的结果。IMHO测试IsNothing(或Object=Nothing,Object Is Nothing)比依赖数据类型的怪癖要好得多。

最好的做法是确保a有一个值,您可以使用来做到这一点

Dim a As Boolean? = New Boolean()
Dim b As Boolean = a

我之所以说这是最佳实践,是因为它适用于所有类,而不仅仅是布尔型。注意到这对布尔人来说太过分了。

希望这能有所帮助。

最新更新