Passing arguments to an event handler

后端 未结 2 1553
日久生厌
日久生厌 2020-12-23 17:01

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

相关标签:
2条回答
  • 2020-12-23 17:43

    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);
    
    0 讨论(0)
  • 2020-12-23 18:04

    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");
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题