按位运算|和|在C#中哪种情况是对还是错 [英] Bitwise operations | And | Which situation is true or false in c#
问题描述
我通过一个例子来展示我的问题:
I show my question by an example :
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 :
不能应用于类型为'bool'和'int'的操作数
Cannot be applied to operands of type 'bool' and 'int'
-
在C#中,何时
b
变量为 true ,而b
变量为 false ?
如何解决该错误?
c ++何时识别出 b
变量为true?另一边应该是(flag& a)!= 0
或(flag& a)== 1
或其他名称?
When does c++ recognize that b
variable is true? The other side should be (flag & a) != 0
or (flag & a) == 1
or something else?
推荐答案
在C#中,您将其编写为:
In C# you write it like so:
bool b = (flag & a) != 0;
在C#中,您不能像在C ++中那样将int分配给bool.
You can't assign an int to a bool in C#, like you can in C++.
(在C ++中,编译器生成的代码实际上与上述代码具有相同的功能,尽管如果您仅尝试将int分配给bool,大多数C ++编译器都会生成警告.)
(In C++ the compiler generates code that effectively does the same as the code above, although most C++ compilers will generate a warning if you just try to assign an int to a bool.)
也请参阅Visual C ++警告C4800 ,它告诉您也用C ++编写这种方式.
Also see the Visual C++ warning C4800, which tells you to write it this way in C++ too.
这篇关于按位运算|和|在C#中哪种情况是对还是错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!