2012-04-22 129 views
0

我有這個代碼,我不明白爲什麼我不能使用運算符||在這個例子中。將bool轉換爲int?

「Operator'||'不能應用於類型'bool'和'int'的操作數「

我錯過了什麼嗎?這個布爾值在哪裏?

int i = 1;        
if (i == 1) 
{ 
    Response.Write("-3"); 
} 
else if (i == 5 || 3) //this is the error, but where is the bool? 
{ 
    Response.Write("-2"); 
} 
+2

哪種語言? – 2012-04-22 22:14:14

+4

這樣做吧 'else if(i == 5 || i == 3)' – 2012-04-22 22:14:43

+0

對不起#2,c#.NET這裏。 當然,謝謝。我幾個月沒有使用這些工具,顯然有點生鏽。 – LaughingMan 2012-04-22 22:17:40

回答

3

您需要將x與y和/或x與z進行比較,在大多數語言中不允許將x與(y或z)進行比較。當你添加一個int的「3」時,bool被引入。編譯器認爲你需要(i == 5)|| (3)這將不會工作,因爲3不會自動轉換爲布爾(除了可能在JavaScript中)。

int i = 1;        
     if (i == 1) 
     { 
      Response.Write("-3"); 
     } 


     else if (i == 5 || i == 3) //this is the error, but where is the bool? 
     { 
      Response.Write("-2"); 
     } 
2

您也可以使用switch-statement。案例3和5的相同

int i = 1; 

     switch (i) 
     { 
      case 1: 
       Response.Write("-3"); 
       break; 
      case 3: 
      case 5: 
       Response.Write("-2"); 
       break; 
     } 

希望這有助於

1

爲什麼你得到一個錯誤的原因是因爲你正試圖執行的東西沒有解決到一個布爾評價布爾方程:

if (false || 3) 

這裏'3'不計算爲布爾方程。

如果你將其更改爲

if (false || 3 == 3) 

這時你會發現它會成功。

+0

是啊,他說什麼... – 2012-04-22 22:26:29