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


当前回答

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/

其他回答

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/

If Bool1 And Bool2 Then

同时计算Bool1和Bool2

If Bool1 AndAlso Bool2 Then

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

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

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


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

And / AndAlso Or / OrElse实际上非常有用。考虑下面的代码,如果函数DoSomethingWihtAandB返回False,它可能不会设置A和/或B:

Dim A,B,C,D As Object
If DoSomethingWithAandB(A,B)=True And A=1 And B=2 Then C=3

如果DoSomethingWithAandB返回False,它将崩溃,因为它将在And之后继续计算,A和B将等于Nothing

Dim A,B,C,D As Object
If DoSomethingWithAandB(A,B)=True AndAlso A=1 AndAlso B=2 Then C=3

如果DoSomethingWithAandB返回False,它不会崩溃,因为它将在DoSomethingWithAandB(A,B)=True时停止求值,因为返回的是False。AndAlso阻止对条件进行任何进一步的计算(因为第一个条件失败了)。OrElse的工作原理与此相同。逻辑链中求值的第一个True将停止任何进一步求值。

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

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