接受的答案没有任何解释,只是一个链接。
因此,我想我会留下一个答案来解释 If 运算符的工作原理,取自 MSDN:
使用短路评估有条件地返回两个之一
价值观。 If 运算符可以用三个参数或两个参数调用
论据。
If( [argument1,] argument2, argument3 )
如果使用两个参数调用运算符
If 的第一个参数可以省略。这使操作员
仅使用两个参数来调用。以下列表适用
仅当使用两个参数调用 If 运算符时。
零件
Term Definition
---- ----------
argument2 Required. Object. Must be a reference or nullable type.
Evaluated and returned when it evaluates to anything
other than Nothing.
argument3 Required. Object.
Evaluated and returned if argument2 evaluates to Nothing.
当 Boolean 参数被省略时,第一个参数必须是
引用或可为空的类型。如果第一个参数计算为
Nothing,返回第二个参数的值。在所有其他情况下,返回第一个参数的值。这
以下示例说明了此评估的工作原理。
VB
' 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))
如何处理两个以上值的示例(嵌套ifs):
Dim first? As Integer = Nothing
Dim second? As Integer = Nothing
Dim third? As Integer = 6
' The LAST parameter doesn't have to be nullable.
'Alternative: Dim third As Integer = 6
' Writes "6", because the first two values are "Nothing".
Console.WriteLine(If(first, If(second, third)))