MouseEventHandler附加参数 - “sender”和“e”无法定义

时间:2013-10-22 07:14:16

标签: c# event-handling argument-passing

我想将一个参数传递给我想用这段代码实现的事件处理程序:

    private void openInputImagesToolStripMenuItem_Click(object sender, EventArgs e)
    {
        ...
        pb.MouseDoubleClick += new MouseEventHandler((sender,e) => showLargeImage(sender,e,imageIndex));
    }

    private void showLargeImage(object sender, MouseEventArgs e, int imageIndex)
    {
        ...
    }

然而,我收到错误的"发件人"和" e"适配器内的变量:

A local variable named 'sender' cannot be declared in this scope because it would give a different meaning to 'sender', which is already used in a 'parent or current' scope to denote something else.

A local variable named 'e' cannot be declared in this scope because it would give a different meaning to 'sender', which is already used in a 'parent or current' scope to denote something else.

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:3)

您不能像编译器告诉您的那样命名lambda方法sendere的参数。

它会在sender方法的参数openInputImagesToolStripMenuItem_Click和lambda方法的参数之间产生歧义。

只需使用其他名称,例如

pb.MouseDoubleClick += new MouseEventHandler((s, e1) => showLargeImage(s, e1,imageIndex));

答案 1 :(得分:1)

应该足以将sender更改为其他内容,例如se

 pb.MouseDoubleClick += 
              new MouseEventHandler((se,e) => showLargeImage(se,e,imageIndex));

答案 2 :(得分:1)

您在lambda中重新定义了sendere,这是不允许的:

private void openInputImagesToolStripMenuItem_Click(object sender, EventArgs e)
{
    ...
    pb.MouseDoubleClick += new MouseEventHandler((s,x) => showLargeImage(sender,e,imageIndex));
}