簡體   English   中英

C#和運營商澄清

[英]C# & operator clarification

我在這里看到了一些關於C#中&&和&運算符之間差異的問題,但我仍然對它的使用方式感到困惑,以及在不同情況下會產生什么結果。 例如,我只是在項目中瞥見了以下代碼

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

當它結果為0並且> 0時? 這個運營商背后的邏輯是什么? 運營商'|'之間有什么區別?

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

我們可以使用&&,|| 運算符並獲得相同的結果(可能使用不同的代碼)?

&&是一個條件,用於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

&符號在二進制表示中對整數執行按位AND運算。 管道按位OR。

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

&和| 是位操作。 你必須在位掩碼上使用它。 &&和|| 是邏輯運算,因此您只能將其用於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 operator - returns 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 operator - returns 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);

bMyBoolean falsenMyInt = 0 ,因為:

  00 
& 01 
= 00;

第二種情況:

bMyBoolean = Convert.ToBoolean(nMyInt & 2);

bMyBoolean falsenMyInt = 01 ,因為

  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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM