Should I always use the AndAlso and OrElse operators?

送分小仙女□ 提交于 2019-11-26 16:48:35

问题


Is there ever a circumstance in which I would not want to use the AndAlso operator rather than the And operator? …or in which I would not want to use the OrElse operator rather than the Or operator?


回答1:


From MSDN:

Short-Circuiting Trade-Offs

Short-circuiting can improve performance by not evaluating an expression that cannot alter the result of the logical operation. However, if that expression performs additional actions, short-circuiting skips those actions. For example, if the expression includes a call to a Function procedure, that procedure is not called if the expression is short-circuited, and any additional code contained in the Function does not run. If your program logic depends on any of that additional code, you should probably avoid short-circuiting operators.




回答2:


Is there ever a circumstance in which I would not want to use the AndAlso operator rather than the And operator?

Sure: if you want to make sure that both sides of the expression are evaluated. This might be the case if, for example, both sides are method calls that return booleans as a result of some other operation that has a side effect.

But in general, use AndAlso/OrElse whenever you would use &&/|| in C/C++/C#, which of course is the vast majority of the time.



来源:https://stackoverflow.com/questions/55013/should-i-always-use-the-andalso-and-orelse-operators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!