将事件绑定到泛型函数

时间:2016-08-30 15:35:27

标签: c# events

是否可以将事件绑定到泛型函数,例如

static void CommonEventHandler(object sender, params object[] values)
{
    //stuff
}

我的理由是,我想使用Lua中的一些事件(使用NLua绑定),它在C#端的函数调用中需要object[]。如果我可以将事件绑定到params函数或类似函数,它将简化我与Lua事件的集成。

1 个答案:

答案 0 :(得分:1)

Lambdas会允许这样做。

你会做这样的事情:

public class MyControl
{
    public MyControl()
    {
        InitializeComponent();

        int myArgs = 123;
        MyButton.Click += (sender, e) => MyCustomMethod(sender, e, myArgs);

    }
    public void MyCustomMethod(object sender, EventArgs e, int myArgs)
    {

        // this prints "123" when the button is pressed
        MessageBox.Show(myArgs.ToString());
    }
}

只需将int myArgs替换为您要使用的参数类型和值。

相关问题