If 运算符 (Visual Basic)

使用短路评估有条件地返回两个值之一。 If可以使用三个参数或两个参数调用运算符。

语法

If( [argument1,] argument2, argument3 )

如果使用三个参数调用运算符

使用三个参数调用时 If ,第一个参数的计算结果必须为可强制转换为值 Boolean。 该值 Boolean 将确定计算并返回其他两个参数中的哪一个。 以下列表仅适用于使用三个参数调用运算符时 If

部件

术语 定义
argument1 必填。 Boolean。 确定要计算和返回的其他参数中的哪一个。
argument2 必填。 Object。 如果 argument1 计算结果为 True,则求值并返回 。
argument3 必填。 Object。 如果 argument1 计算结果为 False Null 或计算结果为 argument1 Null Boolean 变量,则计算结果为 Nothing,则求值并返回。

If使用三个参数调用的运算符的工作方式与函数类似,IIf只不过它使用短路计算。 函数 IIf 始终计算其所有三个参数,而具有三个 If 参数的运算符只计算其中两个参数。 计算第一个IfBoolean参数,结果将强制转换为值,TrueFalse。 如果值为 Trueargument2 则计算值并返回其值,但不 argument3 计算该值。 如果表达式的值 BooleanFalseargument3 则计算并返回其值,但不 argument2 计算。 以下示例演示了使用三个参数时的用法 If

' This statement prints TruePart, because the first argument is true.
Console.WriteLine(If(True, "TruePart", "FalsePart"))

' This statement prints FalsePart, because the first argument is false.
Console.WriteLine(If(False, "TruePart", "FalsePart"))

Dim number = 3
' With number set to 3, this statement prints Positive.
Console.WriteLine(If(number >= 0, "Positive", "Negative"))

number = -1
' With number set to -1, this statement prints Negative.
Console.WriteLine(If(number >= 0, "Positive", "Negative"))

下面的示例演示了短路评估的值。 该示例演示了两次尝试除零时divisor除变量以外的变量。numberdivisor 在这种情况下,应返回 0,并且不应尝试执行除法,因为运行时错误将导致。 If由于表达式使用短路计算,因此它将根据第一个参数的值计算第二个或第三个参数。 如果第一个参数为 true,则除数不为零,并且可以安全地计算第二个参数并执行除法。 如果第一个参数为 false,则只计算第三个参数并返回 0。 因此,当除数为 0 时,不会尝试执行除法,也不会产生错误结果。 但是,由于 IIf 不使用短路计算,因此即使第一个参数为 false,也会计算第二个参数。 这会导致运行时除以零错误。

number = 12

' When the divisor is not 0, both If and IIf return 4.
Dim divisor = 3
Console.WriteLine(If(divisor <> 0, number \ divisor, 0))
Console.WriteLine(IIf(divisor <> 0, number \ divisor, 0))

' When the divisor is 0, IIf causes a run-time error, but If does not.
divisor = 0
Console.WriteLine(If(divisor <> 0, number \ divisor, 0))
' Console.WriteLine(IIf(divisor <> 0, number \ divisor, 0))

如果使用两个参数调用的运算符

可以省略第一个参数 If 。 这样,只能使用两个参数调用运算符。 以下列表仅适用于使用两个参数调用运算符时 If

部件

术语 定义
argument2 必填。 Object。 必须是引用或可以为 null 的值类型。 在计算结果为除其他任何内容外 Nothing,计算结果并返回。
argument3 必填。 Object。 如果 argument2 计算结果为 Nothing,则求值并返回 。

Boolean省略参数时,第一个参数必须是引用或可以为 null 的值类型。 如果第一个参数的计算结果 Nothing为,则返回第二个参数的值。 在所有其他情况下,将返回第一个参数的值。 以下示例演示了此评估的工作原理:

' Variable first is a nullable type.
Dim first? As Integer = 3
Dim second As Integer = 6

' Variable first <> Nothing, so its value, 3, is returned.
Console.WriteLine(If(first, second))

second = Nothing
' Variable first <> Nothing, so the value of first is returned again.
Console.WriteLine(If(first, second))

first = Nothing
second = 6
' Variable first = Nothing, so 6 is returned.
Console.WriteLine(If(first, second))

另请参阅