"<= is an invalid expression term"和") expected"



我正在摆弄C#,并正在制作一个原型GUI(没有附带游戏,只是摆弄按钮和按钮颜色)。我遇到了一个错误:

private void temperValue_Load(object sender, EventArgs e)
    {
        int temperInt = 23;
        temperInt = Convert.ToInt32(temperValue.Text);
        if (temperInt >= 70)
        {
            temperButton.BackColor = System.Drawing.Color.Red;
        }
        else if (temperInt >= 40 & <= 69)
        {
            temperButton.BackColor = System.Drawing.Color.DarkOrange;
        }
    }

在"else-if"行中,"<="one_answers"69)"都有一个错误。"<="错误是"无效的表达式项'<='","69)"的四个错误是")预期的"、"无效表达式项')'"和两个";预期的"错误。

此代码段之外没有任何变量会影响此代码。调用的每个变量都在代码段中定义。

(对于任何好奇的人来说,"Temperature"代表"Temperature")

在这样的布尔条件下不能走捷径。

else if (temperInt >= 40 & <= 69)

必须改为:

else if (temperInt >= 40 && temperInt <= 69)

请注意,在进行布尔比较时,通常需要使用双安培数和&&。这会导致短路(如果左侧成功,只评估两侧),这通常是需要的。正如我所说,两次都需要包含temperInt标识符——不能像SQL BETWEEN子句中那样说"某个变量大于一个值而小于另一个值"。

更新:根据Eric的建议修复了答案。

if (temperInt >= 40 & <= 69) ...

不是有效的C#。计算机语言比自然语言更具限制性。您应该使用:

if (temperInt >= 40 && temperInt <= 69) ...

(您会注意到,我还使用了逻辑&&运算符,而不是逐位&运算符——前者用于真值,后者通常用于位操作,有关详细信息,请参阅此答案)。

还有另一种选择,使用扩展方法:

bool IsBetween (this int me, int lower, int upper) { 
    return (me >= lower) && (me <= upper); 
}
if (temperInt.IsBetween (40, 69)) ...

这更接近自然语言,但对于这种情况来说,这可能有些过头了。

您可能是指temperInt >= 40 && temperInt <= 69

else if (temperInt >= 40 & <= 69)

应为:

else if (temperInt >= 40 && temperInt <= 69)

您需要在语句的两个部分中都包含该变量,&是按位and,而&&是逻辑and,这正是您在本例中想要的。

给定的代码中有一些错误。

 else if (temperInt >= 40 & <= 69)
    {
        temperButton.BackColor = System.Drawing.Color.DarkOrange;
    }

这实际上应该是

 else if (temperInt >= 40 && temperInt <= 69)
    {
        temperButton.BackColor = System.Drawing.Color.DarkOrange;
    }

&amp;是C#中的逻辑AND运算符,而不是'&'。此外,LHS部分需要在所有等式比较中使用,而不是像您的代码示例那样链接。

最新更新