之间的差异的清晰,深入浅出的解释|和||在C#? [英] A clear, layman's explanation of the difference between | and || in c#?

查看:122
本文介绍了之间的差异的清晰,深入浅出的解释|和||在C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,我读过有关这许多次,但我还没有听到一个清晰,易于理解(和难忘的)的方式来学习的区别:

Ok, so I've read about this a number of times, but I'm yet to hear a clear, easy to understand (and memorable) way to learn the difference between:

if (x | y)

if (x || y)

.. C#的范围内。任何人都可以请帮我学这个基本事实,以及如何C#具体而言,不同的对待他们(因为他们似乎做同样的事情)。如果code给定的片断有它们之间的区别是无关紧要的,应该我默认为最佳实践?

..within the context of C#. Can anyone please help me learn this basic truth, and how C# specifically, treats them differently (because they seem to do the same thing). If the difference a given piece of code has between them is irrelevant, which should I default to as a best-practise?

推荐答案

|| 逻辑或的运营商。请参阅 这里 。它的计算结果为真正如果操作数至少有一个为真。您只能使用布尔运算使用它;它与整数操作数使用错误。

|| is the logical-or operator. See here. It evaluates to true if at least one of the operands is true. You can only use it with boolean operands; it is an error to use it with integer operands.

// Example
var one = true || bar();   // result is true; bar() is never called
var two = true | bar();    // result is true; bar() is always called

| 的运营商。请参阅 这里 。如果应用于布尔类型,它的计算结果为真正如果操作数至少有一个为真。如果应用于整数类型,它计算到另一个号码。这个数字有它的每个位设置为1,如果操作数中的至少一个具有相应的位集合

| is the or operator. See here. If applied to boolean types, it evaluates to true if at least one of the operands is true. If applied to integer types, it evaluates to another number. This number has each of its bits set to 1 if at least one of the operands has a corresponding bit set.

// Example
var a = 0x10;
var b = 0x01;
var c = a | b;     // 0x11 == 17
var d = a || b;    // Compile error; can't apply || to integers
var e = 0x11 == c; // True

对于布尔操作数, A || b 是的相同 A | b ,跟单不同的是 B 不评估,如果 A 是真实的。出于这个原因, || 被说成是短路。

For boolean operands, a || b is identical to a | b, with the single exception that b is not evaluated if a is true. For this reason, || is said to be "short-circuiting".

如果差别code给定的片断有他们之间是不相关的,这是我应默认为最佳实践?

If the difference a given piece of code has between them is irrelevant, which should I default to as a best-practise?

如前所述,所不同的是不无关的,所以这个问题是部分无实际意义。作为一个最佳实践,没有一个:您只需使用任何运营商是正确的使用。一般情况下,人们青睐 || | 布尔运算,因为你可以肯定它不会产生不必要的一面的效果。

As noted, the difference isn't irrelevant, so this question is partially moot. As for a "best practice", there isn't one: you simply use whichever operator is the correct one to use. In general, people favor || over | for boolean operands since you can be sure it won't produce unnecessary side effects.

这篇关于之间的差异的清晰,深入浅出的解释|和||在C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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