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

发布于 2024-07-08 23:32:38 字数 76 浏览 7 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

如果没结果 2024-07-15 23:32:38

And 运算符对两边求值,其中 AndAlso 当且仅当左侧为 true 时才对右侧求值。

一个例子:

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/" panopticoncentral.net/2003/08/18/the-ballad-of-andalso-and-orelse/

The And operator evaluates both sides, where AndAlso evaluates the right side if and only if the left side is true.

An example:

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

The above throws an exception if 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 AndAlso like you would use &&.

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

忆沫 2024-07-15 23:32:38

And 运算符将在继续之前检查语句中的所有条件,而 Andalso 运算符在知道条件为 false 时将停止。 例如:

if x = 5 And y = 7

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

if x = 5 AndAlso y = 7

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

通常,如果有理由在第一部分不正确时明确不检查第二部分,例如如果检查时会抛出异常,那么人们会使用短路方法。 例如:

If Not Object Is Nothing AndAlso Object.Load()

如果使用 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:

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.

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

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 And instead of AndAlso, it would still try to Object.Load() even if it were nothing, which would throw an exception.

纸短情长 2024-07-15 23:32:38

有趣的是,没有一个答案提到 VB.NET 中的 AndOr 是位运算符,而 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

注意:非零整数被视为trueDim e = not 0 会将 e 设置为 -1,证明 Not 也是一个位运算符。

||&&OrElseAndAlso 的 C# 版本)返回最后计算的表达式,分别为 35。 这使您可以使用成语 v || C# 中的 5vnull 或 (0 > 和一个整数),否则为 v 的值。 语义上的差异可能会让涉足 VB.NET 的 C# 程序员措手不及,因为这种“默认值习惯用法”在 VB.NET 中不起作用。

所以,回答这个问题:使用OrAnd进行位运算(整数或布尔值)。 使用 OrElseAndAlso “短路”操作以节省时间,或在评估之前测试评估的有效性。 如果有效(评估)并且还评估,则如果无效(不安全(评估)或其他(不评估))则

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

Dim e = Not 0 And 3

Interestingly none of the answers mentioned that And and Or in VB.NET are bit operators whereas OrElse and AndAlso are strictly Boolean operators.

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 0 will set e to -1 demonstrating Not is also a bit operator.

|| and && (the C# versions of OrElse and AndAlso) return the last evaluated expression which would be 3 and 5 respectively. This lets you use the idiom v || 5 in C# to give 5 as the value of the expression when v is null or (0 and an integer) and the value of v 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 and And for bit operations (integer or Boolean). Use OrElse and AndAlso 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 or if not (unsafe(evaluation) orelse (not evaluation)) then

Bonus: What is the value of the following?

Dim e = Not 0 And 3
说好的呢 2024-07-15 23:32:38
If Bool1 And Bool2 Then

计算 Bool1 和 Bool2

If Bool1 AndAlso Bool2 Then

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

If Bool1 And Bool2 Then

Evaluates both Bool1 and Bool2

If Bool1 AndAlso Bool2 Then

Evaluates Bool2 if and only if Bool1 is true.

流绪微梦 2024-07-15 23:32:38

对于那些认为副作用是邪恶的人来说:在一种情况下具有两个副作用是好的地方,那就是同时读取两个文件对象。

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

使用 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.

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

Using the And ensures that a row is consumed every time the condition is checked. Whereas AndAlso might read the last line of File1 and leave File2 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.

薆情海 2024-07-15 23:32:38

AndAlso 很像 And,只不过它的工作方式类似于 && 在 C#、C++ 等中。

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

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

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

如果 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:

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.

流星番茄 2024-07-15 23:32:38

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

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


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

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
偏闹i 2024-07-15 23:32:38

另请参阅 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.

万劫不复 2024-07-15 23:32:38

除了上面的答案之外,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.

似最初 2024-07-15 23:32:38

对于我们大多数人来说,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.

茶花眉 2024-07-15 23:32:38

使用AndOr进行逻辑位运算,例如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 ...

旧人 2024-07-15 23:32:38

用文字而不是代码来理解:

用例:
使用“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.

浅听莫相离 2024-07-15 23:32:38

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 将会崩溃,因为它将在 AndA之后继续计算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,因为返回了FalseAndAlso 阻止对条件进行任何进一步的评估(因为第一个条件失败)。 OrElse 的工作方式相同。 逻辑链中评估的第一个 True 将停止任何进一步的评估。

The And / AndAlso Or / OrElse are actually quite useful. Consider this code, where the function DoSomethingWihtAandB may not set A and/or B if it returns False:

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

It will crash if DoSomethingWithAandB returns False, because it will continue to evaluate after the And and A and B will equal Nothing

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

This won't crash if DoSomethingWithAandB returns False because it will stop evaluating at DoSomethingWithAandB(A,B)=True, because False is returned. The AndAlso prevents any further evaluation of the conditions (as the first condition failed). OrElse works the same way. The first True evaluated in the logic chain will stop any further evaluation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文