在VB。And和AndAlso的区别是什么?我应该用哪一种?


当前回答

一种简单的思考方法是使用更简单的英语

If Bool1 And Bool2 Then
If [both are true] Then


If Bool1 AndAlso Bool2 Then
If [first is true then evaluate the second] Then

其他回答

AndAlso很像And,除了它像c#和c++中的&&一样工作。

区别在于,如果第一个子句(AndAlso之前的子句)为真,那么第二个子句永远不会被求值——复合逻辑表达式是“短路的”。

这有时是非常有用的,例如在这样的表达式中:

If Not IsNull(myObj) AndAlso myObj.SomeProperty = 3 Then
   ...
End If

如果myObj为null,则在上面的表达式中使用旧的And将抛出NullReferenceException。

If Bool1 And Bool2 Then

同时计算Bool1和Bool2

If Bool1 AndAlso Bool2 Then

当且仅当Bool1为真时计算Bool2。

使用And和Or进行逻辑位操作,例如x% = y%或3

AndAlso和OrElse是If语句:

如果x > 3 AndAlso x <= 5那么

If (x > 3) And (x <= 5) Then

在我看来…

同样值得注意的是,(我)建议你在If语句中包含逻辑运算符的方程,这样它们就不会被编译器误解,例如:

If x = (y And 3) And also…

理解:用语言而不是用密码来理解:

用例:使用“And”,编译器将检查所有条件,所以如果你检查一个对象可能是“Nothing”,然后你检查它的一个属性,你将会有一个运行时错误。 但是对于AndAlso,如果条件中第一个“false”,它会检查下一个,这样就不会出现错误。

And运算符求两边的值,而AndAlso运算符求右边的值当且仅当左边为真。

一个例子:

If mystring IsNot Nothing And mystring.Contains("Foo") Then
  ' bla bla
End If

如果mystring = Nothing,则会抛出异常

If mystring IsNot Nothing AndAlso mystring.Contains("Foo") Then
  ' bla bla
End If

这个不抛出异常。

所以如果你来自c#世界,你应该像使用&&一样使用AndAlso。

更多信息请访问:http://www.panopticoncentral.net/2003/08/18/the-ballad-of-andalso-and-orelse/