Passing arguments to an event handler

2019-01-21 16:50发布

问题:

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");
}

回答1:

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");
    }

}


回答2:

If you want to access username and age, you should create handler which uses custom EventArgs (inherited from EventArgs class), like following:


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);