VB.NET 中的 And 和 AndAlso 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/302047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:55:29  来源:igfitidea点击:

What is the difference between And and AndAlso in VB.NET?

vb.netshort-circuiting

提问by Nakul Chaudhary

In VB.NET, what is the difference between Andand AndAlso? Which should I use?

在VB.NET,之间有什么区别AndAndAlso?我应该使用哪个?

回答by Nico

The Andoperator evaluates both sides, where AndAlsoevaluates the right side if and only if the left side is true.

And运算符计算两侧,其中AndAlso检测某个右侧,仅在左侧是真实的。

An example:

一个例子:

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

The above throws an exception if mystring = Nothing

以上抛出异常,如果 mystring = Nothing

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

This one does not throw an exception.

这个不会抛出异常。

So if you come from the C# world, you should use AndAlsolike you would use &&.

因此,如果您来自 C# 世界,则应该AndAlso像使用&&.

More info here: http://www.panopticoncentral.net/2003/08/18/the-ballad-of-andalso-and-orelse/

更多信息在这里:http: //www.panopticoncentral.net/2003/08/18/the-ballad-of-andalso-and-orelse/

回答by Ed Marty

The Andoperator will check all conditions in the statement before continuing, whereas the Andalso operator will stop if it knows the condition is false. For example:

And运营商将检查所有条件的声明,然后再继续,而如果它知道条件是假的Andalso操作将停止。例如:

if x = 5 And y = 7

Checks if x is equal to 5, and if y is equal to 7, then continues if both are true.

检查 x 是否等于 5,如果 y 等于 7,如果两者都为真,则继续。

if x = 5 AndAlso y = 7

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.)

检查 x 是否等于 5。如果不是,它不检查 y 是否为 7,因为它知道条件已经为假。(这称为短路。)

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 Not Object Is Nothing AndAlso Object.Load()

If that used Andinstead of AndAlso, it would still try to Object.Load()even if it were nothing, which would throw an exception.

如果使用And代替AndAlsoObject.Load()即使它是nothing,它仍然会尝试,这将引发异常。

回答by Charles Hymans

Interestingly none of the answers mentioned that Andand Orin VB.NET are bit operators whereas OrElseand AndAlsoare strictly Boolean operators.

有趣的是,没有一个答案提到AndOr在 VB.NET 中是位运算符,而OrElseAndAlso是严格的布尔运算符。

Dim a = 3 OR 5 ' Will set a to the value 7, 011 or 101 = 111
Dim a = 3 And 5 ' Will set a to the value 1, 011 and 101 = 001
Dim b = 3 OrElse 5 ' Will set b to the value true and not evaluate the 5
Dim b = 3 AndAlso 5 ' Will set b to the value true after evaluating the 5
Dim c = 0 AndAlso 5 ' Will set c to the value false and not evaluate the 5

Note: a non zero integer is considered true; Dim e = not 0will set eto -1demonstrating Notis also a bit operator.

注意:考虑非零整数trueDim e = not 0将设置e-1演示Not也是一个位运算符。

||and &&(the C# versions of OrElseand AndAlso) return the last evaluated expression which would be 3and 5respectively. This lets you use the idiom v || 5in C# to give 5as the value of the expression when vis nullor (0and an integer) and the value of votherwise. 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.

||&&(作为C#版本OrElseAndAlso)返回最后计算的表达式这将是35分别。这使您可以使用v || 5C# 中的习语来给出5表达式的值 when vis nullor ( 0and an integer) 和 else 的值v。语义上的差异可能会让涉足 VB.NET 的 C# 程序员措手不及,因为这种“默认值习惯用法”在 VB.NET 中不起作用。

So, to answer the question: Use Orand Andfor bit operations (integer or Boolean). Use OrElseand AndAlsoto "short circuit" an operation to save time, or test the validity of an evaluation prior to evaluating it. If valid(evaluation) andalso evaluation thenor if not (unsafe(evaluation) orelse (not evaluation)) then

所以,回答这个问题:使用OrAnd进行位运算(整数或布尔值)。使用OrElseAndAlso来“短路”操作以节省时间,或在评估之前测试评估的有效性。If valid(evaluation) andalso evaluation then或者if not (unsafe(evaluation) orelse (not evaluation)) then

Bonus:What is the value of the following?

奖励:以下内容的价值是多少?

Dim e = Not 0 And 3

回答by Bryan Anderson

If Bool1 And Bool2 Then

Evaluates both Bool1 and Bool2

计算 Bool1 和 Bool2

If Bool1 AndAlso Bool2 Then

Evaluates Bool2 if and only if Bool1 is true.

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

回答by Ian

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.

只是对于那些说副作用是邪恶的人来说:在一个条件下有两个副作用是好的地方将同时读取两个文件对象。

While File1.Seek_Next_Row() And File2.Seek_Next_Row()
    Str1 = File1.GetRow()
    Str2 = File2.GetRow()
End While

Using the Andensures that a row is consumed every time the condition is checked. Whereas AndAlsomight read the last line of File1and leave File2without a consumed line.

使用And可确保每次检查条件时都会消耗一行。而AndAlso可能会阅读最后一行File1并离开File2而没有消耗的行。

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.

当然上面的代码行不通,但我一直使用这样的副作用,不会认为它是“”或“邪恶”的代码,因为有些人会让你相信。它易于阅读且高效。

回答by rbrill

A simple way to think about it is using even plainer English

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

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


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

回答by Tor Haugen

AndAlso is much like And, except it works like && in C#, C++, etc.

AndAlso 与 And 非常相似,但它的工作方式与 C#、C++ 等中的 && 类似。

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".

不同之处在于,如果第一个子句(AndAlso 之前的那个)为真,则永远不会计算第二个子句 - 复合逻辑表达式是“短路”。

This is sometimes very useful, e.g. in an expression such as:

这有时非常有用,例如在诸如以下的表达式中:

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

Using the old And in the above expression would throw a NullReferenceException if myObj were null.

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

回答by Joel Coehoorn

Also see Stack Overflow question: Should I always use the AndAlso and OrElse operators?.

另请参阅堆栈溢出问题:我应该始终使用 AndAlso 和 OrElse 运算符吗?.

Also: A comment for those who mentioned using Andif the right side of the expression has a side-effect you need:

另外:And如果表达式的右侧有您需要的副作用,则对那些提到使用的人发表评论:

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 bothsides 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.

如果右侧有您需要的副作用,只需将其移动到左侧而不是使用“And”。你只有真正需要“和”如果双方互有副作用。如果你有这么多副作用,你可能做错了其他事情。一般来说,你真的应该更喜欢 AndAlso。

回答by davidallyoung

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.

除了上述答案之外,AndAlso 还提供了一个称为短路的调节过程。许多编程语言都像 vb.net 一样内置了此功能,并且可以通过删除不必要的评估来显着提高长条件语句的性能。

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.

另一个类似的条件是 OrElse 条件,它只会在左侧条件为假时检查右侧条件,从而在找到真条件后删除不必要的条件检查。

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.

我建议您始终使用短路过程,并以最能从中受益的方式构建您的条件语句。例如,首先测试您最有效和最快的条件,以便您只在绝对必须的情况下运行长时间的条件,而其他时间则短路。

回答by Anand

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).

对于我们中的大多数人来说,OrElse 和 AndAlso 会起作用,除了一些令人困惑的例外(不到 1%,我们可能不得不使用 Or 和 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.

它非常简单直接,有时您的系统可能无法按预期工作,因为它首先不喜欢您的逻辑。然而你的大脑不断告诉你,他的逻辑已经过 100% 的测试和证明,它应该有效。在那一刻停止相信你的大脑并要求他再想一想,或者(不是 OrElse 或 OrElse)你强迫自己寻找另一份不需要太多逻辑的工作。