按位运算 |和 | c#中哪种情况是真还是假

Bitwise operations | And | Which situation is true or false in c#

我用一个例子来说明我的问题:

    int a = 1 << 0; // = 1
    int flag = 1;
    bool b = flag & a; // = 1 < In c++ this line has no error but in c# error is like this :

Cannot be applied to operands of type 'bool' and 'int'

  1. b变量为true且当b变量为false时C#?

  2. 如何修复错误?

  3. c++什么时候识别出b变量为真?另一边应该是 (flag & a) != 0(flag & a) == 1 还是别的?

在C#中你可以这样写:

bool b = (flag & a) != 0;

不能像在 C++ 中那样在 C# 中将 int 赋值给 bool。

(在 C++ 中,编译器生成的代码实际上与上面的代码相同,但如果您只是尝试将 int 分配给 bool,大多数 C++ 编译器会生成警告。)

还有see the Visual C++ warning C4800,它告诉你在C++中也这样写。

在C/C++中,false0true是非零​​值(!0)。 C++ 将每个值都视为布尔值(例如,可以测试任何值的真实性)。

在 C# 中,类型得到了更好的强制执行,因此您不能简单地测试数字的真实性。

您必须将结果表达式等同于:

bool b = (flag & a) != 0;