将不同的对象发送到事件处理程序

本文关键字:事件处理 程序 对象 | 更新日期: 2023-09-27 17:55:39

>我有一个组合框数组:

ComboBox[] boxes = new ComboBox[3]{ComboBox box1, ComboBox box2, ComboBox box3};

每个 ComboBox 在其索引更改时都会传递给相同的事件处理程序:

foreach (ComboBox box in boxes)
{
  box.SelectedIndexChanged += new EventHandler(this.Box_Changed);
}

我想做的不是单个 ComboBox,而是将整个 boxes[] 数组传递给事件处理程序。我该怎么做?

将不同的对象发送到事件处理程序

你不能真正改变发送到回调的内容,因为它是由框架代表你调用的。

您可以找到其他地方来存储数据,例如 .标记每个组合框的属性,或者可以创建一个简单的小帮助程序方法,该方法了解 ComboBox,并让它为您传递该数据。

public void Example(ComboBox[] boxes)
{
    // Using a statement lambda to wrap the call
    foreach (ComboBox box in boxes)
    {
        box.SelectedIndexChanged += new EventHandler((sender, e) =>
        {
            Box_Changed_Example1(boxes, sender, e);
        });
    }
    // Or, use the .Tag property to store the data
    foreach (ComboBox box in boxes)
    {
        box.Tag = boxes;
        box.SelectedIndexChanged += new EventHandler(Box_Changed_Example2);
    }
}
void Box_Changed_Example1(ComboBox[] boxes, object sender, EventArgs e)
{
    // TODO
}
void Box_Changed_Example2(object sender, EventArgs e)
{
    ComboBox[] boxes = (ComboBox[])((ComboBox)sender).Tag;
    // TODO
}