Better way of coding this if statement?
I have another question for you very helpful people. I use a lot of if statements many of which are just repeated and I'm sure could be shortened. This is my current bit of code
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;
}
as you can see there is a huge amount of code to do something simple (which I do on a few other forms as well and I'm sure there must be a better way of coding this that gets the same result? I'm a code noob so please be gentle, code is C# and software is Visual studio 2008 pro.
Most of your properties should be arrays (or some other collection). For example:
ScoreUpdate.StandNo6
could be this instead:
ScoreUpdate.StandNos[5]
Then you can use a loop instead of all those if
statements:
for (int i = 0; i < Globals.TotalStands; ++i)
{
ScoreUpdate.StandNos[i].Visible = true;
ScoreUpdate.ScoreStands[i].Visible = true;
ScoreUpdate.ScoreOutOfs[i].Visible = true;
}
Or this slight variation might be better where there is an array of ScoreUpdates rather than three separate arrays:
for (int i = 0; i < Globals.TotalStands; ++i)
{
var scoreUpdate = ScoreUpdates[i];
scoreUpdate.StandNo.Visible = true;
scoreUpdate.ScoreStand.Visible = true;
scoreUpdate.ScoreOutOf.Visible = true;
}
You should make three arrays or lists of controls and use a loop.
精彩评论