重构if语句

时间:2014-05-14 17:24:07

标签: c#

如何让这段代码变得更好?我需要增加 FoodLevel 的值, 3 ,每个新的 PlayersLevel

if (PlayersLevel == 0)
{
    button1.Text = textForFoodButtons[FoodLevel + 0].ToString();
    button3.Text = textForFoodButtons[FoodLevel + 1].ToString();
    button4.Text = textForFoodButtons[FoodLevel + 2].ToString();
}
else if (PlayersLevel == 1)
{
    button1.Text = textForFoodButtons[FoodLevel + 3].ToString();
    button3.Text = textForFoodButtons[FoodLevel + 4].ToString();
    button4.Text = textForFoodButtons[FoodLevel + 5].ToString();
}

1 个答案:

答案 0 :(得分:7)

button1.Text = textForFoodButtons[FoodLevel + PlayersLevel * 3].ToString();
button3.Text = textForFoodButtons[FoodLevel + PlayersLevel * 3 + 1].ToString();
button4.Text = textForFoodButtons[FoodLevel + PlayersLevel * 3 + 2].ToString();