为什么是“&&"而不是“&"? [英] Why '&&' and not '&'?

查看:108
本文介绍了为什么是“&&"而不是“&"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么&&优于&||优于|?

我问了一个已经编程多年的人,他的解释是:

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.如果opnull,则表达式(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,而&|可用于任何整数类型(boolintlongsbyte,... ),因为它们是按位运算符. &按位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:

  1. 对于整数(intuintlongulong,第7.11.1章):
    它们被实现为计算操作数和运算符的按位结果,即&被实现为计算按位逻辑AND等.
  2. 对于枚举(第7.11.2章):
    实现它们是为了执行枚举的基础类型的逻辑操作.
  3. 对于布尔值和可为null的布尔值(第7.11.3和7.11.4章):
    不使用按位计算来计算结果.基本上根据两个操作数的值查找结果,因为可能性很小.
    由于这两个值都用于查找,因此该实现不会造成短路.
  1. For integers (int, uint, long and ulong, 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 logical AND etc.
  2. For enumerations (chapter 7.11.2):
    They are implemented to perform the logical operation of the underlying type of the enumeration.
  3. 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屋!

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