急切操作和短路操作之间的区别? (|与||和&与&&) [英] Difference between eager operation and short-circuit operation? (| versus || and & versus &&)

查看:82
本文介绍了急切操作和短路操作之间的区别? (|与||和&与&&)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我(仍在)学习C#,并且我想我理解& &之间的区别。 & 以及 | & ||| ...

I am (still) learning C# - and I thought I understood the difference between & & && as well as | & ||...

但是,在阅读了另一本指南之后,很明显我不明白。

However, after just reading another guide, it is clear I don't get it.

我写了一个小小的真值表,正如我以为的那样,它们返回相同的值。从我阅读的内容来看,使用双符号听起来是一种更好的解决方案,但是我对此有所困惑,并想知道是否有人可以解释/提供一个示例,说明为什么/何时使用一个而不是另一个-我尝试过阅读MSDN示例,但是它比我刚开始时更加困惑!

I wrote a little truth table and as I thought, they return the same. From what I have read, using double symbols sounds like a superior solution, but I am a little confused on the difference and was wondering if anyone could please explain/give an example why/when you would use one instead of the other - I tried reading the MSDN example, but it left me more confused than when I started!

(而且,如果有人可以提出更好的标题,请随时进行更改...非常尴尬写一个!)

(And, if anyone can come up with a better title, feel free to change it... very awkward to write one!)

推荐答案

&可以以两种不同的方式使用:按位与和逻辑与

& can be used in two different ways: bitwise "and" and logical "and"

逻辑&和&&仅当您使用&时,即使第一个表达式已经为假,第二个表达式也会被求值。例如,如果要在循环中初始化两个变量,这可能很有趣:

The difference between logical & and && is only that in case you use &, the second expression is also evaluated, even if the first expression was already false. This may (for example) be interesting if you want to initialize two variables in the loop:

if ((first = (i == 7)) & (second = (j == 10))) { //do something }

如果您使用这种语法,则如果使用

if you use this syntax, first and second will always have a value, if you use

if ((first = (i == 7)) && (second = (j == 10))) { //do something }


对于| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |和||:如果使用|,则两个表达式都将求值,如果使用||

It is the same for | and ||: In case you use |, both of the expressions are always evaluated, if you use || it may be that only the first expression is evaluated, which would be the case if the first expression is true.

相比之下,在其他应用程序中,&p;可能是更好的选择。如果myNumber的类型为 int?,则可能会出现类似

In contrast, in other applications && can be the better choice. If myNumber is of type int?, you could have something like

if (myNumber != null && myNumber.Value == 7)

首先评估 myNumber!= null ,并且如果空检查还可以,它只会评估第二个表达式。

and this would only evaluate myNumber != null at first, and it would only evaluate the second expression, if the null check was okay.

if (myNumber != null & myNumber.Value == 7)


$ b如果myNumber为null,则在第二个表达式的求值过程中$ b

将以NullPointerException结尾。因此,您将使用&&在这种情况下。

would finish with a NullPointerException during the evaluation of the second expression, if myNumber was null. Therefore, you would use && in this context.

这篇关于急切操作和短路操作之间的区别? (|与||和&与&&)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆