如何循环执行此switch语句?
我想在单击另一个按钮时更改3种按钮颜色。我需要在情况4到情况1之间无限循环。 我愿意接受其他任何解决方案。
private void Next_Click(object sender, EventArgs e)
{
i++;
switch (i)
{
case 1:
red.BackColor = Color.Red;
orange.BackColor = Color.Black;
green.BackColor = Color.Black;
break;
case 2:
red.BackColor = Color.Red;
oragne.BackColor = Color.Orange;
green.BackColor = Color.Black;
break;
case 3:
red.BackColor = Color.Black;
orange.BackColor = Color.Black;
green.BackColor = Color.Green;
break;
case 4:
red.BackColor = Color.Black;
orange.BackColor = Color.Orange;
green.BackColor = Color.Black;
break;
}
}
答案 0 :(得分:0)
使用Integer余数,将满足您的需求。非零余数的符号与左操作数的符号相同
private void Next_Click(object sender, EventArgs e)
{
switch (i++ % 4)
{
case 0:
red.BackColor = Color.Red;
orange.BackColor = Color.Black;
green.BackColor = Color.Black;
break;
case 1:
red.BackColor = Color.Red;
oragne.BackColor = Color.Orange;
green.BackColor = Color.Black;
break;
case 2:
red.BackColor = Color.Black;
orange.BackColor = Color.Black;
green.BackColor = Color.Green;
break;
case 3:
red.BackColor = Color.Black;
orange.BackColor = Color.Orange;
green.BackColor = Color.Black;
break;
}
}
更多阅读此处:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators