C# 将参数传递给事件处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12293471/
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
Passing arguments to an event handler
提问by user476566
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.ageand e.name?
在下面的代码中,我定义了一个事件处理程序,并希望从中访问年龄和名称变量,而无需全局声明名称和年龄。有什么办法可以说e.age和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");
}
采纳答案by ColinE
Yes, you could define the event handler as a lambda expression:
是的,您可以将事件处理程序定义为 lambda 表达式:
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");
}
}
回答by MaciekTalaska
If you want to access username and age, you should create handler which uses custom EventArgs (inherited from EventArgs class), like following:
如果您想访问用户名和年龄,您应该创建使用自定义 EventArgs(继承自 EventArgs 类)的处理程序,如下所示:
public class ProcessEventArgs : EventArgs
{
public string Name { get; internal set; }
public int Age { get; internal set; }
public ProcessEventArgs(string Name, int Age)
{
this.Name = Name;
this.Age = Age;
}
}
and the delegate
和代表
public delegate void ProcessHandler (object sender, ProcessEventArgs data);

