lambda表达式的事件

Lin*_*nas 2 c# lambda winforms

我需要有人帮我解决这个小问题.这是一段代码片段:

void shuffle() 
{
    for (int i = 0; i < 4; i++) {

        // here should be the computations of x and y

        buttons[i].Click += (s, e) => { show_coordinates(x, y); };

        // shuffling going on
    }
}

void show_coordinates(int x, int y)
{
    MessageBox.Show(x + " " + y);
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,每次运行循环时,我都会为每个按钮创建一个具有不同x和y的新事件处理程序.在我的表单中有另一个按钮,随机地按下按钮.

所以这就是问题所在:如果我按下随机按钮说10次,然后按任意洗牌按钮,事件处理程序就会叠加,我会得到10个显示x和y值的消息框.

那么每次按shuffle时,如何用新的事件处理程序覆盖前一个事件处理程序.

提前致谢.

Mag*_*nus 7

我会重新设计代码而不是这样做:

private PointF[] points = new PointF[4];

//Run once
public void Initialize()
{
    for (int i = 0; i < 4; i++)
        buttons[i].Click += (s, e) => { show_coordinates(i); };
}

public void Shuffle()
{
    for (int i = 0; i < 4; i++) 
    {
        // here should be the computations of x and y
        points[i] = new PointF(x,y);
        // shuffling going on
    }
}

public void show_coordinates(int index)
{
    var point = points[index];
    MessageBox.Show(point.X + " " + point.Y);
}
Run Code Online (Sandbox Code Playgroud)