将参数传递给事件处理程序

时间:2012-09-06 05:25:55

标签: c# events event-handling handler

在下面的代码中,我定义了一个事件处理程序,并希望从中访问age和name变量,而不是全局声明名称和年龄。有没有办法说e.agee.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");
}

2 个答案:

答案 0 :(得分:61)

是的,您可以将事件处理程序定义为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");
    }

}

答案 1 :(得分:11)

如果要访问用户名和年龄,则应创建使用自定义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;
  }
}

和代表

public delegate void ProcessHandler (object sender,  ProcessEventArgs data);