按钮数组的Click事件

use*_*564 1 c# windows button winforms

我在C#WFA中有一个Button数组,我想为单击数组中的任何按钮创建一个事件。我该怎么做?以及如何知道它在数组中的哪个位置?我知道发件人是按钮本身

Ser*_*rvy 5

您可以使用一个for循环来封闭包含当前索引的变量:

for(int i = 0; i < buttons.Length; i++)
{
    //it's important to have this; closing over the loop variable would be bad
    int index = i;  
    buttons[i].Click += (sender, args) => SomeMethod(buttons[index], index);
}
Run Code Online (Sandbox Code Playgroud)