[英]Delegates C#: Pass current method EventArgs to another method
private void button1_Click(object sender, EventArgs e)
{
//code
//error saying local variable named e can't be passed
this.timer1[i].Tick += new System.EventHandler((s,e)=>this.timer1_Tick(s,e,i));
//code
}
private void timer1_Tick(object sender, EventArgs e, int i)
{
//code
}
两种方法都需要相同的eventArgs。 问题是因为我还需要将我也传递给第二种方法。 还有其他方法吗?
您需要更清楚地了解要执行的操作- 您不会将事件参数传递给计时器的Tick
事件; 计时器会。 您要做的只是附加一个事件处理程序,该事件处理程序在引发计时器的Tick
事件时将被调用。 如果希望计时器的Tick
事件处理程序引用传递给Click
事件的事件args的某些部分,则将其存储在类属性或事件处理程序可以访问的位置。
或者,如果您在Tick
事件处理程序中具有要在单击按钮时执行一次的代码,则将其移至一个单独的函数中,该事件既可以在Click
事件中也可以在Tick
事件中调用。 简单地附加事件处理程序不会执行它。
private void button1_Click(object sender, EventArgs e)
{
this.timer1[i].Tick += new System.EventHandler((local_s,local_e)=>this.timer1_Tick(local_s,local_e,i));
//code
}
private void timer1_Tick(object sender, EventArgs e, int i)
{
//code
}
private void Button1_Click(object sender, EventArgs args)
{
Timer1.Tick += (s, a) =>
{
//Anonymous delegate can access the sender and args
//parameters and variables of the outer scope.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.