在表达式中使用IIf

use*_*195 2 vb.net

假设totallvl是一个整数并且chclass1已经创建但是chclass2没有,为什么我可以这样做:

totallvl = chclass1.level
If chclass2 IsNot Nothing Then
    totallvl = totallvl + chclass2.level
End If
Run Code Online (Sandbox Code Playgroud)

但不是吗?

totallvl = chclass1.level + IIf(chclass2 Is Nothing, 0, chclass2.level) 
Run Code Online (Sandbox Code Playgroud)

这就像编译器假设我将chclass2在此示例中使用但不在第一个示例中.

Ry-*_*Ry- 5

IIf只是一个功能; chclass2.level无论第一个参数是什么,都会被评估.如果您想要一个与其他语言类似的内联条件运算符,请使用实际的内联If(在VB 2008及更高版本中可用):

If(chclass2 Is Nothing, 0, chclass2.level)
Run Code Online (Sandbox Code Playgroud)