简体   繁体   English

常规OR(|)和常规AND(&)运算符是否有实际用途

[英]Is there a practical use for regular OR (|) and regular AND (&) operator

I was looking up some beginner lessons on "csharp-station.com" to review my knowledge on C#. 我在“ csharp-station.com”上查找了一些初学者课程,以回顾我对C#的了解。 For AND and OR operators, I've always used "&&" and "||" 对于AND和OR运算符,我一直使用“ &&”和“ ||” like everybody else. 像其他人一样 I didn't even know there is a single version of those. 我什至不知道它们只有一个版本。

It's stated as follows: 内容如下:

About OR: "The primary difference between the two OR forms are that the regular OR operator will evaluate both sub-expressions every time. However, the conditional OR will evaluate the second sub-expression only if the first sub-expression evaluates to false." 关于OR:“两种OR形式之间的主要区别在于,常规OR运算符每次都会对两个子表达式进行求值。但是,只有在第一个子表达式的求值为false时,条件OR才会对第二个子表达式求值。 “

About AND: "The difference between the two is that the regular AND operator will evaluate both expressions every time. However, the conditional AND operator will evaluate the second sub-expression only when the first sub-expression evaluates to true." 关于AND:“两者之间的区别在于,常规AND运算符每次都会对两个表达式进行求值。但是,条件AND运算符仅在第一个子表达式求值为true时才对第二个子表达式求值。”

And it concludes as: "The conditional operators (&& and ||) are commonly called short-circuit operators because they do not always evaluate the entire expression. Thus, they are also used to produce more efficient code by ignoring unnecessary logic." 它的结论是:“条件运算符(&&和||)通常被称为短路运算符,因为它们并不总是对整个表达式求值。因此,它们也被用来通过忽略不必要的逻辑来产生更有效的代码。”

So is that all? 那就是全部吗? Is there even a single code sample where using the regular operators are more plausible? 在使用常规运算符的情况下,甚至没有一个单一的代码示例? I know the question is trivial, but I'm just curious. 我知道这个问题很简单,但我很好奇。 Thanks in advance. 提前致谢。

As you say, these operators don't short-circuit. 如您所说,这些运算符不会短路。 But that's not all: they're used for bit manipulation. 但这还不是全部:它们用于位操作。 Some examples: 一些例子:

Set the 4th bit: 设置第4位:

// 00000010 | 00001000 == 00001010
value = value | (1 << 3);

Clear the 4th bit: 清除第四位:

// ~00001000 == 11110111
// 00001010 & 11110111 == 00000010
value = value & ~(1 << 3);

Check if the 4th bit is set: 检查第4位是否被设置:

// 00001010 & 00001000 == 00001000
if ((value & (1 << 3)) != 0)
   ...

In C#, this is commonly used with flag enums ( enum types with the [Flags] attribute applied). 在C#中,这通常与标志枚举(使用[Flags]属性的enum类型)一起使用。

Here's an example from the framework: 这是框架中的一个示例:

[Flags]
public enum FileAttributes
{
    ReadOnly = 0x1,
    Hidden = 0x2,
    System = 0x4,
    Directory = 0x10,
    Archive = 0x20,
    Device = 0x40,
    Normal = 0x80,

    // and so on...
}

So for instance you could test if a file is hidden using code like: 因此,例如,您可以使用以下代码测试文件是否被隐藏:

if ((attributes & FileAttributes.Hidden) != 0)
    ...

The main difference is if the expressions have side effects and if you want those side effects to always occur 主要区别在于表达式是否具有副作用,以及是否希望这些副作用始终发生

public bool A()
{
    Console.WriteLine("A");
    return true;
}

public bool B()
{
    Console.WriteLine("B");
    return false;
}

With the above methods the following 使用上述方法,以下

if(A() || B())
    Console.WriteLine("A or B");

and this 和这个

if(A() | B())
    Console.WriteLine("A or B");

Will print out different results. 将打印出不同的结果。

With that said depending on these side effects is a bad idea. 说这些依赖这些副作用是一个坏主意。 So, in general the use of non-short-curcuited logical operators is only useful for cases that would be considered poor design. 因此,通常,非短命逻辑运算符的使用仅对那些被认为是不良设计的情况有用。 So, any time you find that you need to use them it most likely means there is a flaw in the design of the code. 因此,每当您发现需要使用它们时,很可能意味着代码设计中存在缺陷。

But as others have mentioned the & and | 但是正如其他人提到的&| operators are also used for bitwise "AND" and "OR", which is different from using them with bool expressions. 运算符还用于按位“ AND”和“ OR”,这与在bool表达式中使用它们不同。

They perform binary (base 2) calculations. 它们执行二进制(基数2)计算。 See bitwise operations . 请参阅按位运算

|  OR   
&  AND
^  XOR
~  NOT

These are the basic machine operations, used by all computers. 这些是所有计算机使用的基本机器操作。
Computers love them, but most programmers prefer decimal arithmetic and enums. 计算机喜欢它们,但是大多数程序员更喜欢十进制算术和枚举。

There's hypothetical scenarios for these operators. 这些运营商有假设的情况。 As already written, all of them involve side-effects. 如前所述,它们都具有副作用。

Imagine, you have a web-registration form with username , password , confirmation fields. 想象一下,您有一个包含usernamepasswordconfirmation字段的网络注册表单。

You should validate user's input after POST. 您应该在POST之后验证用户的输入。 You're planning to use simple validation methods that returns bool , fe IsUsernameAvailable , IsUsernameValid , IsPasswordComplexEnough , and ArePasswordAndConfirmationEquals . 您打算使用简单的验证方法来返回bool ,fe IsUsernameAvailableIsUsernameValidIsPasswordComplexEnoughArePasswordAndConfirmationEquals All of these methods has a single input/output parameter IList<string> containing error messages. 所有这些方法都有一个包含错误消息的单个输入/输出参数IList<string>

Then your entire validation method may look like this: 然后,您的整个验证方法可能如下所示:

private bool ValidateAll(IList<string> errorMessages)
{
    return IsUsernameAvailable(errorMessages)
         | IsUsernameValid(errorMessages)
         | IsPasswordComplexEnough(errorMessages)
         | ArePasswordAndConfirmationEquals(errorMessages);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM