2

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

totallvl = chclass1.level
If chclass2 IsNot Nothing Then
    totallvl = totallvl + chclass2.level
End If

但不是这个?

totallvl = chclass1.level + IIf(chclass2 Is Nothing, 0, chclass2.level) 

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

4

2 回答 2

5

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

If(chclass2 Is Nothing, 0, chclass2.level)
于 2013-01-20T02:51:25.817 回答
2

这是因为调用函数时所有函数参数都已解析。if 语句仅在语句块的“true”部分运行代码。

于 2013-01-20T02:50:26.910 回答