将事件设置为数组C#中的对象

我有一个标签数组,我想添加鼠标输入,并在这些标签上留下事件。


该标签是通过编程方式创建的:


            Label [] lblData = new Label[255];

        int calcLoc = 0;

        for (int i = 0; i <= 200; i++)

        {

            calcLoc = 25 * i;

            lblData[i] = new Label();

            lblData[i].Location = new Point(10, calcLoc);

            lblData[i].Text = "Test " + i;

            InfoPanel.Controls.Add(lblData[i]);


        }

我尝试过的事情:在循环中设置事件(显然是行不通的)


lblData[i].MouseEnter += (sender, e) => {lblData[i].BackColor = Color.LightBlue;};

在循环之前设置事件(有可能这样做)


lblData[].MouseEnter += (sender, e) => {lblData[].BackColor = Color.LightBlue;};

都不起作用。


慕容3067478
浏览 189回答 2
2回答

白板的微信

您可以使用单个方法和sender参数。这是经过最少更改的代码。您可以为所有事件设置一个独立的静态方法,然后选中sender。lblData[i].MouseEnter += (sender, e) => {((Label)sender).BackColor = Color.LightBlue;};所有Label实例都可以订阅的更安全且速度稍快的版本。出于以下原因,静态方法的性能更好,您可以避免使用闭包,这可以确保事件由触发Label。private static void label_MouseEnter(object sender, EventArgs e){&nbsp; &nbsp;var label = sender as Label;&nbsp; &nbsp;if (label == null)&nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp;label.BackColor = Color.LightBlue;}

阿晨1998

这个怎么样?Label[] lblData = new Label[255];int calcLoc = 0;for (int i = 0; i <= 200; i++){&nbsp; &nbsp; calcLoc = 25 * i;&nbsp; &nbsp; Label label = new Label();&nbsp; &nbsp; label.Location = new Point(10, calcLoc);&nbsp; &nbsp; label.Text = "Test " + i;&nbsp; &nbsp; label.MouseEnter += (sender, e) =>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; label.BackColor = Color.LightBlue;&nbsp; &nbsp; };&nbsp; &nbsp; InfoPanel.Controls.Add(label);&nbsp; &nbsp; lblData[i] = label;}甚至这个:Label[] lblData =&nbsp; &nbsp; Enumerable&nbsp; &nbsp; &nbsp; &nbsp; .Range(0, 201)&nbsp; &nbsp; &nbsp; &nbsp; .Select(i =>&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var calcLoc = 25 * i;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Label label = new Label();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; label.Location = new Point(10, calcLoc);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; label.Text = "Test " + i;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; label.MouseEnter += (sender, e) =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; label.BackColor = Color.LightBlue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; InfoPanel.Controls.Add(label);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return label;&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; .ToArray();
打开App,查看更多内容
随时随地看视频慕课网APP