“&”的用法与“&&” [英] Usage of '&' versus '&&'

查看:110
本文介绍了“&”的用法与“&&”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个问题:

bool Isvalid = isValid & CheckSomething()

bool Isvalid = isValid && CheckSomething()

第二种情况可能是发生短路的情况。

The second case could be a scenario for short circuiting.

所以我们不能总是只使用& 而不是&

So can't we always use just & instead of &&?

推荐答案

& 按位 AND,表示它在位级别起作用。 & 逻辑的,这意味着它可以在布尔(真/假)级别工作。逻辑AND使用短路(如果第一部分为假,则没有用处检查第二部分)来防止运行过多的代码,而按位AND则需要对每一位进行操作才能确定结果。

& is a bitwise AND, meaning that it works at the bit level. && is a logical AND, meaning that it works at the boolean (true/false) level. Logical AND uses short-circuiting (if the first part is false, there's no use checking the second part) to prevent running excess code, whereas bitwise AND needs to operate on every bit to determine the result.

您应该使用逻辑AND(&& ),因为这就是您想要的,而& 可以可能做错了事。但是,如果要评估其副作用,则需要单独运行第二种方法:

You should use logical AND (&&) because that's what you want, whereas & could potentially do the wrong thing. However, you would need to run the second method separately if you wanted to evaluate its side effects:

var check = CheckSomething();
bool IsValid = isValid && check;

这篇关于“&”的用法与“&&”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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