如何循环此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;
}
}
使用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