C#背面颜色变化

时间:2018-09-03 12:30:00

标签: c#

我刚刚开始在大学学习C#,但遇到了一些问题。单击带有if语句的一个按钮时,需要更改背景色。我的代码是这样的:

BackColor = Color.Red;
if ( BackColor == Color.Red)
{
    BackColor = Color.Blue;
}
if (BackColor == Color.Blue)
{
    BackColor = Color.Green;
}

问题在于背景颜色会立即变为绿色。我应该怎么做才能将其更改为三种颜色?抱歉,问题很愚蠢。

3 个答案:

答案 0 :(得分:8)

您需要了解if condition。第一个if的值为true,因为您刚刚将Color.Red分配给BackColor,然后第二个if的值也为true,因为您刚刚为其分配了Color.Blue

另外,如果您使用BackColor初始化Color.Red,则第一个将始终为true,因此将以Blue的方式进行初始化。我想您想这样做:

 if (BackColor == Color.Green) 
 {
     BackColor = Color.Red;
 }
 else if (BackColor == Color.Red)
 {
     BackColor = Color.Blue;
 }
 else if (BackColor == Color.Blue)
 {
     BackColor = Color.Green;
 }

我建议您阅读有关if conditions的更多信息。另外,如Rotem建议的那样,也请查看有关switch的信息。

答案 1 :(得分:1)

仅在不强制使用“ if”的情况下适用:

class xyz{
    private Color[] myColors = new Color[]{ Color.Red, Color.Blue, Color.Green }
    private int colorIndex = 0;

    // BackColor also declared somewhere here ...

    private void clickHandler( object sender, EventArgs e )
    {
         colorIndex = (++colorIndex)%myColors.length; 
         // ++ColorIndex is short for colorIndex = colorIndex + 1
         // % - "Remainder" => when colorIndex is 3 then 3 % 3 ( Remainder of 3 / 3 ) = 0
         // So this will increment on each click and "reset to 0" on 3, so you stay in bounds.
         BackColor = myColors[ colorIndex ];
    }
}

答案 2 :(得分:0)

将其放入构造函数中

BackColor = Color.Green;

而且这在onclick方法中

if (BackColor == Color.Green) 
{
    BackColor = Color.Red; 
} 
else if (BackColor == Color.Red)
{
    BackColor = Color.Blue;
} 
else if (BackColor == Color.Blue)
{ 
    BackColor = Color.Green; 
}

那应该对你有用