C# 在运行时绑定事件时将附加参数传递给事件处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18234201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:36:06  来源:igfitidea点击:

C# pass additional parameter to an event handler while binding the event at the run time

c#asp.netmethodsparametersarguments

提问by foo-baar

I have a link button which have a regular click event :

我有一个链接按钮,它有一个常规的点击事件:

protected void lnkSynEvent_Click(object sender, EventArgs e)
{
}

And I bind this event at the runtime :

我在运行时绑定这个事件:

lnkSynEvent.Click += new EventHandler(lnkSynEvent_Click);

Now I need the function to accept additional argument:

现在我需要函数来接受额外的参数:

protected void lnkSynEvent_Click(object sender, EventArgs e, DataTable dataT)
{
}

And pass the same as parameter while binding this event :

并在绑定此事件时传递与参数相同的参数:

lnkSynEvent.Click += new EventHandler(lnkSynEvent_Click, //somehow here);

Not sure how to achieve this. Please help.

不知道如何实现这一点。请帮忙。

Thanks in advance.

提前致谢。

Vishal

维沙尔

采纳答案by alex

You can use anonymous delegate for that:

您可以为此使用匿名委托:

lnkSynEvent.Click += 
         new EventHandler((s,e)=>lnkSynEvent_Click(s, e, your_parameter));

回答by nivethitha

by use of delegate:

通过使用委托:

lnkbtnDel.Click += delegate(object s, EventArgs e1) { 
                 Dynamic_Click(s, e1, lnkbtnDel.ID); 
               };`  

回答by ErazerBrecht

I don't know exactly when it's changed, but now it's even easier!

我不知道它什么时候改变,但现在更容易了!

lnkSynEvent.Click += (s,e) => lnkSynEvent_Click(s, e, your_parameter);

回答by CarLoOSX

EventHandler myEvent = (sender, e) => MyMethod(myParameter);//my delegate

myButton.Click += myEvent;//suscribe
myButton.Click -= myEvent;//unsuscribe

private void MyMethod(MyParameterType myParameter)
{
 //Do something
}