我有另一个问题,对你非常有帮助的人。我使用了很多if语句,其中很多都是重复的,我确信可以缩短。这是我目前的代码
if (Globals.TotalStands <= 1)
{
ScoreUpdate.StandNo2.Visible = false;
ScoreUpdate.ScoreStand2.Visible = false;
ScoreUpdate.ScoreOutOf2.Visible = false;
}
if (Globals.TotalStands <= 2)
{
ScoreUpdate.StandNo3.Visible = false;
ScoreUpdate.ScoreStand3.Visible = false;
ScoreUpdate.ScoreOutOf3.Visible = false;
}
if (Globals.TotalStands <= 3)
{
ScoreUpdate.StandNo4.Visible = false;
ScoreUpdate.ScoreStand4.Visible = false;
ScoreUpdate.ScoreOutOf4.Visible = false;
}
if (Globals.TotalStands <= 4)
{
ScoreUpdate.StandNo5.Visible = false;
ScoreUpdate.ScoreStand5.Visible = false;
ScoreUpdate.ScoreOutOf5.Visible = false;
}
if (Globals.TotalStands <= 5)
{
ScoreUpdate.StandNo6.Visible = false;
ScoreUpdate.ScoreStand6.Visible = false;
ScoreUpdate.ScoreOutOf6.Visible = false;
}
if (Globals.TotalStands <= 6)
{
ScoreUpdate.StandNo7.Visible = false;
ScoreUpdate.ScoreStand7.Visible = false;
ScoreUpdate.ScoreOutOf7.Visible = false;
}
if (Globals.TotalStands <= 7)
{
ScoreUpdate.StandNo8.Visible = false;
ScoreUpdate.ScoreStand8.Visible = false;
ScoreUpdate.ScoreOutOf8.Visible = false;
}
正如你所看到的那样,有大量的代码可以做一些简单的事情(我也会在其他几种形式上做这些事情,我确信必须有一种更好的编码方式才能获得相同的结果?我这是一个代码noob,所以请保持温和,代码是C#,软件是Visual Studio 2008专业版。
答案 0 :(得分:8)
您的大多数属性应该是数组(或其他一些集合)。例如:
ScoreUpdate.StandNo6
可能是这样的:
ScoreUpdate.StandNos[5]
然后您可以使用循环而不是所有if
语句:
for (int i = 0; i < Globals.TotalStands; ++i)
{
ScoreUpdate.StandNos[i].Visible = true;
ScoreUpdate.ScoreStands[i].Visible = true;
ScoreUpdate.ScoreOutOfs[i].Visible = true;
}
或者,如果有一组ScoreUpdates而不是三个独立的数组,这种轻微变化可能会更好:
for (int i = 0; i < Globals.TotalStands; ++i)
{
var scoreUpdate = ScoreUpdates[i];
scoreUpdate.StandNo.Visible = true;
scoreUpdate.ScoreStand.Visible = true;
scoreUpdate.ScoreOutOf.Visible = true;
}
答案 1 :(得分:1)
你应该制作三个数组或控件列表并使用循环。