开发者

Reducing similar commands

How can I reduce the amount of similar commands into a loop?

Something like

pictureBox7.BackColor = Color.FromArgb(187, 187, 187);
pictureBox9.BackColor = Color.FromArgb开发者_如何转开发(187, 187, 187);
pictureBox10.BackColor = Color.FromArgb(187, 187, 187);
pictureBox11.BackColor = Color.FromArgb(187, 187, 187);
pictureBox12.BackColor = Color.FromArgb(187, 187, 187);
pictureBox13.BackColor = Color.FromArgb(187, 187, 187);


var pics = new PictureBox[] {pictureBox7, 
                             pictureBox8, 
                             pictureBox9, 
                             pictureBox10, etc... };, 
pics.ToList().ForEach(p => p.BackColor = Color.FromArgb(187, 187, 187));


As implied by the other answers, you need to gather the controls which you want to perform the same operation on into some sort of List, then you can loop over it to set all controls to the same value. A good way to do this would be to have a methods which adds the control to a private list and then another method which applies whatever operation to each control in the list. This allows you to easily add more later without having to dig through code or do excessive amounts of copy-n-paste coding.

Once you do this you can stop naming your controls Control## and start giving them actual descriptive names as to what their purpose is. Having automatically named controls in a working project is a bad idea, as later you'll be beating your head against the wall trying to remember what pictureBox28 is actually for, whereas pictureBoxPreview has a slightly more obvious reason for existing.


Color color = Color.FromArgb(187, 187, 187);
foreach (Control ctrl in this.Controls)
{
    if (ctrl is PictureBox) // don't get me started on is vs. as
    {
        PictureBox pb = (PictureBox)ctrl;
        pb.BackColor = color;
    }
}


PictureBox[] pbs = new PictureBox[]{ pictureBox1, pictureBox2, ...};
for(int i = 0; i < pbs.Length; i++) pbs[i].BackColor = Color.FromARGB(187,187,187)


You could do something like the following. Note, the syntax might not be perfect, but you get the idea.

foreach(var pb in new PictureBox[] {pictureBox7, pictureBox9, pictureBox10, pictureBox11, pictureBox12, pictureBox13})
    pb.BackColor = Color.FromArgb(187, 187, 187);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜