C#和运营商澄清

我在这里看到了一些关于C#中&&和&运算符之间差异的问题,但我仍然对它的使用方式感到困惑,以及在不同情况下会产生什么结果。 例如,我只是在项目中瞥见了以下代码

bMyBoolean = Convert.ToBoolean(nMyInt & 1); bMyBoolean = Convert.ToBoolean(nMyInt & 2); 

当它结果为0并且> 0时? 这个运营商背后的逻辑是什么? 运营商’|’之间有什么区别?

 bMyBoolean = Convert.ToBoolean(nMyInt | 1); bMyBoolean = Convert.ToBoolean(nMyInt | 2); 

我们可以使用&&,|| 运算符并获得相同的结果(可能使用不同的代码)?

&符号在二进制表示中对整数执行按位AND运算。 管道按位OR。

在这里看一下这些按位操作意味着什么: http : //en.wikipedia.org/wiki/Bitwise_operation

&&是一个条件,用于if语句和while

 if(x>1 && y<3) 

这意味着x应大于1且y小于3,满足两个条件

 if(x>1 || y<3) 

满足其中一个

但是,&和| 分别是按位AND和OR。 例如:

  1 | 0 => 1 1 & 0 => 0 1 & 1 => 1 

如果这适用于直整数,则将计算并应用它们相应的二进制值

 2&1 => 10 // the binary value of 2 & 01 // the binary value of 1 -- 00 // the result is zero 

&和| 是位操作。 你必须在位掩码上使用它。 &&和|| 是逻辑运算,因此您只能将其用于bool值。

位操作示例:

 var a = 1; var b = 2; var c = a|b; 

在二进制格式中,这意味着a = 00000001,b = 00000010 c = 00000011

因此,如果使用位掩码c,它将传递值1,2或3。

另一个区别是&运算符计算其操作数的逻辑按位AND,如果操作数不是bool(在您的情况下为整数)

& operator is BItwise AND运算符,它对位进行操作。 例如5和3

  0101 //5 0011 //3 ---------- 5&3= 0001 //1 

| operator is BItwise OR | operator is BItwise OR运算符,它对位进行操作。 5 | 3

  0101 //5 0011 //3 ---------- 5|3= 0111 //7 

&&运算符是logical AND operatorreturns true if all conditions are truereturns true if all conditions are true
例如

  if((3>5)&&(3>4)) //returns true if((6>5)&&(3>4)) //returns false 

|| operator是logical OR operatorreturns true if one of the conditions is truereturns true if one of the conditions is true
例如

  if((3>5)||(3>4)) //returns true if((6>5)||(3>4)) //returns true if((6>5)||(5>4)) //returns false 

其他答案为您解释了&&和&之间的不同,所以假设您理解这一点。 在这里,我只是试着解释你指定的情况。

第一个案例

 bMyBoolean = Convert.ToBoolean(nMyInt & 1); 

nMyInt = 0时, nMyInt = 0 false ,因为:

  00 & 01 = 00; 

第二种情况:

 bMyBoolean = Convert.ToBoolean(nMyInt & 2); 

nMyInt = 01nMyInt = 0 false ,因为

  00 & 10 = 00; 

要么:

  01 & 10 = 00; 

第三和第四种情况是按位| 是微不足道的,因为bMyBoolean对于任何nMyInt始终为true

 bMyBoolean = Convert.ToBoolean(nMyInt | 1); bMyBoolean = Convert.ToBoolean(nMyInt | 2); 

你不能申请&&或|| 在这种情况下,因为它们只是bool约束,你将编译错误。

这里有一些有趣的东西。 按顺序,它可以用于bool,如下例所示。

 bool result = true; result &= false; Console.WriteLine("result = true & false => {0}", result ); //result = true & false => False result = false; result &= false; Console.WriteLine("result = false & false => {0}", result ); //result = false & false => False result = true; result &= true; Console.WriteLine("result = true & true => {0}", result ); //result = true & true => True