3 回答
TA贡献1850条经验 获得超11个赞
将If()运算符与两个参数一起使用(Microsoft文档):
' 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))
TA贡献1818条经验 获得超11个赞
接受的答案没有任何解释,仅是一个链接。
因此,我想留下一个解释该If操作员如何工作的答案,取自MSDN:
如果运算符(Visual Basic)
使用短路评估有条件地返回两个值之一。该如果操作员可以用三个参数或两个参数来调用。
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.
当布尔省略参数,所述第一参数必须是参考或空类型。如果第一个参数的计算结果为 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)))
- 3 回答
- 0 关注
- 294 浏览
添加回答
举报