在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”,它会检查下一个,这样就不会出现错误。
推荐文章
- .Net数据结构:ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary—速度,内存,以及何时使用每个?
- 如何以编程方式将Word文件转换为PDF ?
- HTML编码问题-显示“”字符而不是“ ”
- 是否可以在。net中以彩色方式写入控制台?
- VB.NET中的And和AndAlso有什么区别?
- 如何检查树枝为空?
- 使用c#在文本中插入制表符
- 我如何让我的c#程序睡眠50毫秒?
- 堆栈的目的是什么?我们为什么需要它?
- 我如何获得一个人类可读的文件大小字节缩写使用。net ?
- Visual Studio跳转到下一个错误快捷方式?
- 两个日期之间的月差
- 对于WCF客户端“使用”块问题,最好的解决方案是什么?
- Python是否支持短路?
- 什么时候我应该使用List vs LinkedList