为什么是“&&"而不是“&"? [英] Why '&&' and not '&'?
问题描述
为什么&&
优于&
而||
优于|
?
我问了一个已经编程多年的人,他的解释是:
I asked someone who's been programming for years and his explanation was:
例如,在if (bool1 && bool2 && bool3) { /*DoSomething*/ }
中,bool1
必须为真,才能测试bool2
,在继续使用bool3
之前必须为bool2
,依此类推.如果我只使用一个&
相反,即使所有这些都必须是真实的才能前进到下一行,也没有测试的顺序,那为什么为什么这么重要呢?
For example, in if (bool1 && bool2 && bool3) { /*DoSomething*/ }
, bool1
has to be true for it to test bool2
which has to be true before moving on to bool3
, etc. If I'd used a single &
instead there is no order to the test even if all of them have to be true to progress to the next line, so why does it matter anyway?
注意:我想指出的是,我在编程上等同于蹒跚学步,这不是一个严重或紧急的问题.更多的是要理解为什么应该以某种方式而不是另一种方式来完成事情.
Note: I'd like to point out that I'm the programming equivalent of a toddler and this is not a serious or urgent question. It's more a matter of understanding why things should be done a certain way as opposed to another.
推荐答案
在大多数情况下,与&
和|
相比,首选&&
和||
,因为前者是短路的,这意味着评估结果一经清除,即被取消.
In most cases, &&
and ||
are preferred over &
and |
because the former are short-circuited, meaning that the evaluation is canceled as soon as the result is clear.
示例:
if(CanExecute() && CanSave())
{
}
如果CanExecute
返回false
,则完整表达式将为false
,而与CanSave
的返回值无关.因此,不会执行CanSave
.
If CanExecute
returns false
, the complete expression will be false
, regardless of the return value of CanSave
. Because of this, CanSave
is not executed.
在以下情况下这非常方便:
This is very handy in the following circumstance:
string value;
if(dict.TryGetValue(key, out value) && value.Contains("test"))
{
// Do Something
}
如果在词典中找不到提供的密钥,则
TryGetValue
返回false
.由于&&
的短路特性,当TryGetValue
返回true
时,仅执行value.Contains("test")
,因此value
不是null
.如果改用按位AND 运算符&
,则在字典中找不到键时,将得到NullReferenceException
,因为无论如何都要执行表达式的第二部分.
TryGetValue
returns false
if the supplied key is not found in the dictionary. Because of the short-circuiting nature of &&
, value.Contains("test")
is only executed, when TryGetValue
returns true
and thus value
is not null
. If you would use the bitwise AND operator &
instead, you would get a NullReferenceException
if the key is not found in the dictionary, because the second part of the expression is executed in any case.
与此类似但更简单的示例是以下代码(如TJHeuvel所述):
A similar but simpler example of this is the following code (as mentioned by TJHeuvel):
if(op != null && op.CanExecute())
{
// Do Something
}
仅当op
不是null
时才执行
CanExecute
.如果op
为null
,则表达式(op != null
)的第一部分求值为false
,其余部分(op.CanExecute()
)的求值被跳过.
CanExecute
is only executed if op
is not null
. If op
is null
, the first part of the expression (op != null
) evaluates to false
and the evaluation of the rest (op.CanExecute()
) is skipped.
除此之外,从技术上讲,它们也有所不同:
&&
和||
仅可用于bool
,而&
和|
可用于任何整数类型(bool
,int
,long
,sbyte
,... ),因为它们是按位运算符. &
是按位AND 运算符,而|
是按位OR 运算符.
Apart from this, technically, they are different, too:
&&
and ||
can only be used on bool
whereas &
and |
can be used on any integral type (bool
, int
, long
, sbyte
, ...), because they are bitwise operators. &
is the bitwise AND operator and |
is the bitwise OR operator.
确切地说,在C#中,这些运算符(&
,|
[和^
])被称为逻辑运算符"(请参见
To be very exact, in C#, those operators (&
, |
[and ^
]) are called "Logical operators" (see the C# spec, chapter 7.11). There are several implementations of these operators:
- 对于整数(
int
,uint
,long
和ulong
,第7.11.1章):
它们被实现为计算操作数和运算符的按位结果,即&
被实现为计算按位逻辑AND
等. - 对于枚举(第7.11.2章):
实现它们是为了执行枚举的基础类型的逻辑操作. - 对于布尔值和可为null的布尔值(第7.11.3和7.11.4章):
不使用按位计算来计算结果.基本上根据两个操作数的值查找结果,因为可能性很小.
由于这两个值都用于查找,因此该实现不会造成短路.
- For integers (
int
,uint
,long
andulong
, chapter 7.11.1):
They are implemented to compute the bitwise result of the operands and the operator, i.e.&
is implement to compute the bitwise logicalAND
etc. - For enumerations (chapter 7.11.2):
They are implemented to perform the logical operation of the underlying type of the enumeration. - For bools and nullable bools (chapter 7.11.3 and 7.11.4):
The result is not computed using bitwise calculations. The result is basically looked up based on the values of the two operands, because the number of possibilities is so small.
Because both values are used for the lookup, this implementation isn't short-circuiting.
这篇关于为什么是“&&"而不是“&"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!