将参数传递给事件处理程序 [英] Passing arguments to an event handler

查看:129
本文介绍了将参数传递给事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码,我定义事件处理程序,并希望访问从年龄和名字变量没有宣布在全球范围的姓名和年龄。有没有一种方法,我可以说 e.age e.name



 无效测试(字符串名称,字符串岁)
{
流程myProcess =新工艺();
myProcess.Exited + =新的EventHandler(myProcess_Exited);
}

私人无效myProcess_Exited(对象发件人,发送System.EventArgs)
{
//我想在这里访问的用户名和年龄。 ////////////////
eventHandled = TRUE;
Console.WriteLine(处理退出);
}


解决方案

是的,你可以定义事件处理程序作为一个lambda表达式:

 无效测试(字符串名称,字符串岁)
{
流程myProcess =新工艺();
myProcess.Exited + =(发件人,EventArgs)=>
{
//名字和年龄在这里访问的!
eventHandled = TRUE;
Console.WriteLine(处理退出);
}

}


In the below code, I am defining an event handler and would like to access the age and name variable from that without declaring the name and age globally. Is there a way I can say e.age and e.name?

void Test(string name, string age)
{
    Process myProcess = new Process(); 
    myProcess.Exited += new EventHandler(myProcess_Exited);
}

private void myProcess_Exited(object sender, System.EventArgs e)
{
  //  I want to access username and age here. ////////////////
    eventHandled = true;
    Console.WriteLine("Process exited");
}

解决方案

Yes, you could define the event handler as a lambda expression:

void Test(string name, string age)
{
  Process myProcess = new Process(); 
  myProcess.Exited += (sender, eventArgs) =>
    {
      // name and age are accessible here!!
      eventHandled = true;
      Console.WriteLine("Process exited");
    }

}

这篇关于将参数传递给事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆