简体   繁体   English

C#背颜色变化

[英]C# back color change

I just started studying C# in university and I have a problem with something. 我刚开始在大学学习C#,我遇到了问题。 I need to make the back color change when I click one button with if-statement. 当我用if语句单击一个按钮时,我需要进行背面颜色更改。 My code is this: 我的代码是这样的:

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

The problem is the back color changes to green instantly.. what should I do to make it change in the three colors? 问题是背面颜色立即变为绿色......我该怎么做才能让它改变三种颜色? Sorry if the question is dumb. 对不起,如果问题是愚蠢的。

You need to understand the if condition s. 你需要了解if condition The first if evaluates to true because you just assigned Color.Red to BackColor then the second if is also true because you just assigned Color.Blue to it. 第一个if计算为true因为你刚刚将Color.Red分配给BackColor然后第二个if也是true,因为你刚刚为它分配了Color.Blue

Also if you initialize BackColor with Color.Red the first will be always true so it will be Blue this way. 此外,如果使用Color.Red初始化BackColor ,则第一个将始终为true,因此这将是Blue I guess you want to do this: 我想你想这样做:

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

I would suggest you to read more about if conditions . 我建议你阅读更多有关条件的信息 Also, like Rotem suggested, please check about switch too. 另外,像Rotem建议的那样,请检查一下开关

Applies only if the use of "if" is not mandatory: 仅当使用“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 ];
    }
}

Put this in the constructor 把它放在构造函数中

BackColor = Color.Green;

And but this inside the onclick method 但是这个在onclick方法中

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

That should work for you 这对你有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM