-1

我有这段代码,但我不明白为什么我不能使用运算符 || 在这个例子中。

“操作员'||' 不能应用于“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");
}
4

3 回答 3

3

您需要将 x 与 y 和/或 x 与 z 进行比较,大多数语言都不允许将 x 与(y 或 z)进行比较。当您添加一个 int 的“3”时,引入了 bool。编译器认为你想要 (i == 5) || (3) 这不起作用,因为 3 不会自动转换为 bool (可能在 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");
        }
于 2012-04-22T22:17:09.940 回答
2

您还可以使用 switch 语句。案例3和5是同一个
例子

int i = 1;

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

希望这可以帮助

于 2012-04-22T22:17:24.367 回答
1

您收到错误的原因是因为您尝试对无法解析为布尔方程的事物执行布尔评估:

if (false || 3)

这里 '3' 不会计算为布尔方程。

如果你把它改成

if (false || 3 == 3)

然后你会发现它会起作用。

于 2012-04-22T22:20:48.033 回答