False
:Dim b As Boolean? = Nothing
Dim myString = If(b, "True", "False")
为什么那样可以工作?
The documentation clearly states that the three-argument version of
If
requires aBoolean
as the first parameter:argument1 Required. Boolean. Determines which of the other arguments to evaluate and return.
and there is no implicit conversion from
Boolean?
toBoolean
:Dim b1 As Boolean? = Nothing Dim b2 As Boolean = b1 ' Fails with the following error: ' Option Strict On disallows implicit conversions ' from 'Boolean?' to 'Boolean'.
那么,为什么这个方法有效呢?这是编译器中的一个错误(或者“隐藏特性”),还是文档中的一个错误,并且Boolean?
实际上是If(a, b, c)
第一个参数的有效类型?
PS:在C#中,如果b
的类型为bool?
,则b ? x : y
无法编译。
编辑:我已经向Microsoft Connect报告了这个问题。微软的某位工作人员已回复并确认文档将会更新,包括Boolean?
这种情况。
IF
三元运算符。更新到 4.0 后,它变成了IF
而不是IFF
。显然这是反编译器试图通过 IL 重构 VB.Net。实际的 IL 命令是brtrue.s
,它是“如果为真则跳转”,通常被转换为三元运算符。 - Chris Haas