简体   繁体   English

可以使用按位运算符代替逻辑运算符(例如OR)吗

[英]Is it ok to use bitwise operator in place of a logical operator like OR

This may be stupid.but i have a simple doubt Suppose i have the following check in a function 这可能是愚蠢的。但是我有一个简单的疑问,假设我在函数中进行了以下检查

bool Validate(string a , string b)
{
    if(a == null || b == null)
    {
        throw new NullReferenceException();
    }
    else
    {
    }
}

Is it ok to use bitwise OR for validation as shown below 可以使用按位或进行验证,如下所示

if(a == null | b == null)

In boolean expressions (rather than integers etc), the main difference is: short-circuiting. 在布尔表达式(而不是整数等)中,主要区别是:短路。 || short-circuits. 短路。 | does not. 才不是。 In most cases you want short-circuiting, so || 在大多数情况下,您短路,所以|| is much much more common. 更为常见。 In your case, it won't matter, so || 对于您而言,这无关紧要,所以|| should probably be used as the more expected choice. 应该被用作更期望的选择。

The times it matters is: 重要的时刻是:

if(politics.IsCeasefire() | army.LaunchTheRockets()) {
    // ...
}

vs: vs:

if(politics.IsCeasefire() || army.LaunchTheRockets()) {
    // ...
}

The first always does both (assuming there isn't an exception thrown); 第一个总是做这两个 (假设没有抛出异常); the second doesn't launch the rockets if a ceasefire was called. 如果要求停火,第二个也不会发射火箭。

In this case (with bool arguments) the | 在这种情况下(与bool参数)的| operator is not a bitwise operator. 运算符不是按位运算符。 It's just a non-short-circuiting version of the logical or ( || ). 它只是逻辑or|| )的非短路版本。

The same goes for & vs. && - it's just a non-short-circuiting version of logical and . & vs. && -这只是逻辑and的非短路版本。

The difference can be seen with side-effects, for example in 可以从副作用中看出差异,例如

bool Check()
{
    Console.WriteLine("Evaluated!");
    return true;
}

// Short-circuits, only evaluates the left argument.
if (Check() || Check()) { ... }

// vs.

// No short circuit, evaluates both.
if (Check() | Check()) { ... }

This should work, because when used on things that evaluate to bool , the "bitwise" operators carry out logical operations just the same. 这应该行得通,因为当在评估为bool事物上使用时,“按位”运算符将执行相同的逻辑运算。 You might find it less efficient, though. 但是,您可能会发现它效率较低。 The logical operators in C# will short-circuit, meaning they'll skip evaluation of the second expression if the answer can be deduced from the first. C#中的逻辑运算符将短路,这意味着如果可以从第一个表达式中得出答案,则它们将跳过对第二个表达式的求值。 So in your example, if a == null turns out to be true, then || 因此,在您的示例中,如果a == null变为true,则|| would return true immediately, while | 将立即返回true ,而| would go ahead and check b == null anyway. 会继续检查b == null

As has been commented upon, the code is indeed 'ok'. 如前所述,该代码确实是“确定”的。

Using the single pipe '|' 使用单管道“ |” will evaluate all expressions before returning the result. 将在返回结果之前对所有表达式求值。 '||' '||' can be more efficient, since it ceases as soon as an expression evaluates to true. 可以提高效率,因为表达式一经计算为true就立即终止。

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

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