VB.NET 中 And 和 AndAlso 有什么区别?
在 VB.NET 中,And
和 AndAlso
之间有什么区别? 我应该使用哪个?
In VB.NET, what is the difference between And
and AndAlso
? Which should I use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
And
运算符对两边求值,其中AndAlso
当且仅当左侧为 true 时才对右侧求值。一个例子:
如果
mystring = Nothing
上面的代码会抛出异常这个不会抛出异常。
所以如果如果您来自 C# 世界,则应该像使用
&&
一样使用AndAlso
。更多信息请参见:http://www.panopticoncentral.net/2003/08/18/the-ballad-of-andalso-and-orelse/" panopticoncentral.net/2003/08/18/the-ballad-of-andalso-and-orelse/
The
And
operator evaluates both sides, whereAndAlso
evaluates the right side if and only if the left side is true.An example:
The above throws an exception if
mystring = Nothing
This one does not throw an exception.
So if you come from the C# world, you should use
AndAlso
like you would use&&
.More info here: http://www.panopticoncentral.net/2003/08/18/the-ballad-of-andalso-and-orelse/
And 运算符将在继续之前检查语句中的所有条件,而 Andalso 运算符在知道条件为 false 时将停止。 例如:
检查 x 是否等于 5,y 是否等于 7,如果两者都为 true,则继续。
检查 x 是否等于 5。如果不等于,则不会检查 y 是否为 7,因为它知道条件已经为 false。 (这称为短路。)
通常,如果有理由在第一部分不正确时明确不检查第二部分,例如如果检查时会抛出异常,那么人们会使用短路方法。 例如:
如果使用
And
而不是AndAlso
,它仍然会尝试Object.Load()
,即使它什么也没有。 ,这会抛出异常。The
And
operator will check all conditions in the statement before continuing, whereas the Andalso operator will stop if it knows the condition is false. For example:Checks if x is equal to 5, and if y is equal to 7, then continues if both are true.
Checks if x is equal to 5. If it's not, it doesn't check if y is 7, because it knows that the condition is false already. (This is called short-circuiting.)
Generally people use the short-circuiting method if there's a reason to explicitly not check the second part if the first part is not true, such as if it would throw an exception if checked. For example:
If that used
And
instead ofAndAlso
, it would still try toObject.Load()
even if it werenothing
, which would throw an exception.有趣的是,没有一个答案提到 VB.NET 中的
And
和Or
是位运算符,而OrElse
和AndAlso
是严格的布尔运算符。注意:非零整数被视为
true
;Dim e = not 0
会将e
设置为-1
,证明Not
也是一个位运算符。||
和&&
(OrElse
和AndAlso
的 C# 版本)返回最后计算的表达式,分别为3
和5
。 这使您可以使用成语v || C# 中的 5
当v
为null
或 (0
> 和一个整数),否则为v
的值。 语义上的差异可能会让涉足 VB.NET 的 C# 程序员措手不及,因为这种“默认值习惯用法”在 VB.NET 中不起作用。所以,回答这个问题:使用
Or
和And
进行位运算(整数或布尔值)。 使用OrElse
和AndAlso
“短路”操作以节省时间,或在评估之前测试评估的有效性。如果有效(评估)并且还评估,则
或如果无效(不安全(评估)或其他(不评估))则
奖励:价值是多少以下的?
Interestingly none of the answers mentioned that
And
andOr
in VB.NET are bit operators whereasOrElse
andAndAlso
are strictly Boolean operators.Note: a non zero integer is considered
true
;Dim e = not 0
will sete
to-1
demonstratingNot
is also a bit operator.||
and&&
(the C# versions ofOrElse
andAndAlso
) return the last evaluated expression which would be3
and5
respectively. This lets you use the idiomv || 5
in C# to give5
as the value of the expression whenv
isnull
or (0
and an integer) and the value ofv
otherwise. The difference in semantics can catch a C# programmer dabbling in VB.NET off guard as this "default value idiom" doesn't work in VB.NET.So, to answer the question: Use
Or
andAnd
for bit operations (integer or Boolean). UseOrElse
andAndAlso
to "short circuit" an operation to save time, or test the validity of an evaluation prior to evaluating it.If valid(evaluation) andalso evaluation then
orif not (unsafe(evaluation) orelse (not evaluation)) then
Bonus: What is the value of the following?
计算 Bool1 和 Bool2
当且仅当 Bool1 为 true 时才计算 Bool2。
Evaluates both Bool1 and Bool2
Evaluates Bool2 if and only if Bool1 is true.
对于那些认为副作用是邪恶的人来说:在一种情况下具有两个副作用是好的地方,那就是同时读取两个文件对象。
使用
And
可确保每次检查条件时都会消耗一行。 而AndAlso
可能会读取File1
的最后一行,并留下File2
而不使用消耗的行。当然,上面的代码不起作用,但我一直使用这样的副作用,并且不会将其视为“坏”或“邪恶”代码,因为某些会让你相信。 它易于阅读且高效。
Just for all those people who say side effects are evil: a place where having two side effects in one condition is good would be reading two file objects in tandem.
Using the
And
ensures that a row is consumed every time the condition is checked. WhereasAndAlso
might read the last line ofFile1
and leaveFile2
without a consumed line.Of course the code above wouldn't work, but I use side effects like this all the time and wouldn't consider it "bad" or "evil" code as some would lead you to believe. It's easy to read and efficient.
AndAlso 很像 And,只不过它的工作方式类似于 && 在 C#、C++ 等中。
区别在于,如果第一个子句(AndAlso 之前的子句)为 true,则永远不会计算第二个子句 - 复合逻辑表达式被“短路”。
这有时非常有用,例如在诸如以下的表达式中:
如果 myObj 为 null,则在上面的表达式中使用旧的 And 将抛出 NullReferenceException。
AndAlso is much like And, except it works like && in C#, C++, etc.
The difference is that if the first clause (the one before AndAlso) is true, the second clause is never evaluated - the compound logical expression is "short circuited".
This is sometimes very useful, e.g. in an expression such as:
Using the old And in the above expression would throw a NullReferenceException if myObj were null.
一个简单的思考方法是使用更简单的英语
A simple way to think about it is using even plainer English
另请参阅 Stack Overflow 问题:我应该始终使用 AndAlso 和 OrElse 运算符吗?。
另外:对于那些提到使用
And
如果表达式的右侧有您需要的副作用的人的评论:如果右侧有您需要的副作用,只需将其移到左侧而不是使用“和”。 如果双方都有副作用,你才真正需要“And”。 如果你出现了这么多副作用,那么你可能做错了其他事情。 一般来说,您确实应该更喜欢 AndAlso。
Also see Stack Overflow question: Should I always use the AndAlso and OrElse operators?.
Also: A comment for those who mentioned using
And
if the right side of the expression has a side-effect you need:If the right side has a side effect you need, just move it to the left side rather than using "And". You only really need "And" if both sides have side effects. And if you have that many side effects going on you're probably doing something else wrong. In general, you really should prefer AndAlso.
除了上面的答案之外,AndAlso 还提供了一种称为短路的调节过程。 许多编程语言都像 vb.net 一样内置了此功能,并且可以通过删除不必要的计算来显着提高长条件语句的性能。
另一个类似的条件是 OrElse 条件,它仅在左侧条件为 false 时才检查右侧条件,从而在找到 true 条件后删除不必要的条件检查。
我建议您始终使用短路流程并以最能从中受益的方式构建条件语句。 例如,首先测试最有效和最快的条件,以便仅在绝对必要时运行长条件,而在其他时间短路。
In addition to the answers above, AndAlso provides a conditioning process known as short circuiting. Many programming languages have this functionality built in like vb.net does, and can provide substantial performance increases in long condition statements by cutting out evaluations that are unneccessary.
Another similar condition is the OrElse condition which would only check the right condition if the left condition is false, thus cutting out unneccessary condition checks after a true condition is found.
I would advise you to always use short circuiting processes and structure your conditional statements in ways that can benefit the most by this. For example, test your most efficient and fastest conditions first so that you only run your long conditions when you absolutely have to and short circuit the other times.
对于我们大多数人来说,OrElse 和 AndAlso 就可以解决问题,除了一些令人困惑的例外(不到 1% 的情况下我们可能必须使用 Or 和 And)。
尽量不要被人们炫耀他们的布尔逻辑并使其看起来像火箭科学一样得意忘形。
它非常简单直接,有时您的系统可能无法按预期工作,因为它一开始就不喜欢您的逻辑。 然而你的大脑不断告诉你,他的逻辑已经过 100% 的测试和证明,应该有效。 在那一刻,停止相信你的大脑并要求他再考虑一下,或者(不是 OrElse 或 OrElse)你强迫自己寻找另一份不需要太多逻辑的工作。
For majority of us OrElse and AndAlso will do the trick except for a few confusing exceptions (less than 1% where we may have to use Or and And).
Try not to get carried away by people showing off their boolean logics and making it look like a rocket science.
It's quite simple and straight forward and occasionally your system may not work as expected because it doesn't like your logic in the first place. And yet your brain keeps telling you that his logic is 100% tested and proven and it should work. At that very moment stop trusting your brain and ask him to think again or (not OrElse or maybe OrElse) you force yourself to look for another job that doesn't require much logic.
使用And和Or进行逻辑位运算,例如
x% = y% Or 3
AndAlso和 OrElse 用于 If 语句:
If x > 3 AndAlso x <= 5 Then
与
If (x > 3) And (x <= 5) Then
相同 我的看法...
也值得注意(我)建议您将带有逻辑运算符的方程式括在 If 语句中,这样编译器就不会误解它们,例如:
If x = (y And 3)还有...
Use And and Or for logical bit operations, e.g.
x% = y% Or 3
AndAlso and OrElse are for If statements:
If x > 3 AndAlso x <= 5 Then
is same as
If (x > 3) And (x <= 5) Then
The way I see it...
Also it's worth noting that it's recommended (by me) that you enclose equations with logical operators in If statements, so they don't get misinterpreted by the compiler, for example:
If x = (y And 3) AndAlso ...
用文字而不是代码来理解:
用例:
使用“And”,编译器将检查所有条件,因此,如果您正在检查一个对象可能是“Nothing”,然后您正在检查它的其中一个属性,您将出现运行时错误。
但是使用 AndAlso 时,如果条件中第一个“假”,它会检查下一个,这样就不会出现错误。
To understand with words not cods:
Use Case:
With “And” the compiler will check all conditions so if you are checking that an object could be “Nothing” and then you are checking one of it’s properties you will have a run time error.
But with AndAlso with the first “false” in the conditions it will checking the next one so you will not have an error.
And
/AndAlso
Or
/OrElse
实际上非常有用。 考虑以下代码,其中函数DoSomethingWihtAandB
如果返回False
则可能不会设置A
和/或B
:如果
DoSomethingWithAandB
返回False
将会崩溃,因为它将在And
和A
和之后继续计算B
将等于Nothing
如果
DoSomethingWithAandB
返回False
,则不会崩溃,因为它将在DoSomethingWithAandB(A ,B)=True
,因为返回了False
。AndAlso
阻止对条件进行任何进一步的评估(因为第一个条件失败)。OrElse
的工作方式相同。 逻辑链中评估的第一个True
将停止任何进一步的评估。The
And
/AndAlso
Or
/OrElse
are actually quite useful. Consider this code, where the functionDoSomethingWihtAandB
may not setA
and/orB
if it returnsFalse
:It will crash if
DoSomethingWithAandB
returnsFalse
, because it will continue to evaluate after theAnd
andA
andB
will equalNothing
This won't crash if
DoSomethingWithAandB
returnsFalse
because it will stop evaluating atDoSomethingWithAandB(A,B)=True
, becauseFalse
is returned. TheAndAlso
prevents any further evaluation of the conditions (as the first condition failed).OrElse
works the same way. The firstTrue
evaluated in the logic chain will stop any further evaluation.