在条件中使用按位运算符 - 无法将类型“int”隐式转换为“bool”

Use of bitwise operator in condition - Cannot implicitly convert type `int' to `bool'

我编写了以下代码,它使用 bitField 变量作为字符映射来检查它们在给定字符串中的存在:

public static bool AllElementsUniqueInASCIIString(string str) {
    int bitField = 0;
    
    foreach (int character in str) {
        int idx = character - 'a';
        int mask = 1 << idx;
        if (bitField | mask == 1)
            return false;
        else
            bitField &= mask;
    }
    
    return true;
}

问题是,在表达式 if (bitField | mask == 1) 上,编译时会抛出以下错误:

CS0029: Cannot implicitly convert type 'int' to 'bool'

然而,当我用下面的代码片段替换这一行时,代码编译得很好:

   int present = bitField | mask;
   if (present == 1) 

bitFieldmask都是整数,这个编译错误是怎么回事?我应该使用什么语法在一行中检查此条件?

您需要括号来明确表达您的意图

if ((bitField | mask) == 1)

编译器认为您想要执行以下操作(由于运算符优先级)

if (bitField | (mask == 1))
      int    |    bool

错误告诉你的是什么

CS0019 Operator '|' cannot be applied to operands of type 'int' and 'bool'

简而言之,相等运算符优先于布尔逻辑或按位逻辑或运算符


其他资源

Operator precedence

In an expression with multiple operators, the operators with higher precedence are evaluated before the operators with lower precedence