28

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

2 回答 2

64

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

}
于 2012-09-06T05:29:06.380 回答
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);
于 2012-09-06T05:31:48.983 回答