带图片框的 C# 反射

C# Reflection with Picture Box

我想做以下事情:

          string WhoIsTheSender="pictureBox1";

        switch (WhoIsTheSender)
        {
           case "pictureBox1":  
                    pictureBox1.Image = Properties.Resources.ledOff; 
                    break;
           case "pictureBox2":  
                    pictureBox2.Image = Properties.Resources.ledOff;
                    break;
            //....until case "pictureBox64":  pictureBox64.Image = Properties.Resources.ledOff;
                    break;
        }       

有没有办法让它更短?如何使用反射?

string WhoIsTheSender="pictureBox1";
        WhoIsTheSender.Image = Properties.Resources.ledOff; //in this specific example WhoIsTheSender="pictureBox1";            

提前感谢您的帮助!

Yes it is an event, basically I have 64 picture boxes which go to the same event. I don't want to handle all the events separately, so I have 1 event only.

您需要的信息已在活动的 sender 参数中提供。

如果您确定 sender 始终是 PictureBox,那么一行(非反射)就可以:

(PictureBox(sender)).Image = Properties.Resources.ledOff;

如果您不确定 sender 类型,请先测试一下:

var picBox = sender as PictureBox;

if (picBox != null)
    picBox.Image = Properties.Resources.ledOff;