I just recently encountered this issue myself, and searching for this issue has turned up no fruits yet...
So let's say I have four checkboxes, as an example, and I want to do certain things based on which of them are checked at any time...
if (CB1.Checked)
{
//Do things here if only checkbox 1 is checked.
}
else if (CB2.Checked)
{
//Do things here if only checkbox 2 is checked.
}
else if (CB3.Checked)
{
//Do things here if only checkbox 3 is checked.
}
else //if (CB4.Checked)
{
//Do things here if only checkbox 4 is checked.
}
I'm sure most people will tend to use something like the example code snippet above, or a variation of it. It looks simple, right? But what if... you aren't just checking for only one checkbox alone?
if (CB1.Checked && CB2.Checked)
{
//Do things here if only checkbox 1 & 2 is checked.
}
else if (CB2.Checked && CB3.Checked)
{
//Do things here if only checkbox 2 & 3 is checked.
}
else if (CB3.Checked && CB1.Checked)
{
//Do things here if only checkbox 3 & 1 is checked.
}
else if (CB4.Checked && CB1.Checked)
{
//Do things here if only checkbox 4 & 1 is checked.
}
else if (CB4.Checked && CB2.Checked)
{
//Do things here if only checkbox 4 & 2 is checked.
}
else //if (CB4.Checked && CB3.Checked)
{
//Do things here if only checkbox 4 & 3 is checked.
}
As can be seen... the number of if-else statements have increased... And it will, if you wanted to compare perhaps even more checkboxes than 4, or for more checkboxes out of 4... And that could complicate things, with (likely) most programmers being unable to avoid it.
So, my question is... is there a better (or more efficient, or can reduce the lines of code) way to do things according to which checkbox/checkboxes is/are checked? Or are we really stuck to this method (or variations of this method)?
Do note that for this example, whatever you would be doing according to which checkboxes are checked... can't simply be "added on" or "appended".
It should also be noted that the switch-case method will be more or less the same as this method... so it would most likely not make a difference.
Aucun commentaire:
Enregistrer un commentaire