lambda表达式和事件处理程序?

有人向我提到c#支持使用lambda表达式作为事件处理程序,有人可以与我分享一些参考吗?

代码段是首选。

您可以使用lambda表达式来构建匿名方法,该方法可以附加到事件。

例如,如果您使用ButtonLabel制作Windows窗体,则可以在构造函数中添加(在InitializeComponent() ):

  this.button1.Click += (o,e) => { this.label1.Text = "You clicked the button!"; }; 

这将导致标签在单击按钮时更改。

试试这个例子

 public Form1() { InitializeComponent(); this.button1.Click += new EventHandler(button1_Click); } void button1_Click(object sender, EventArgs e) { } 

可以使用此lambda表达式重写上述事件处理程序

  public Form1() { InitializeComponent(); this.button1.Click += (object sender, EventArgs e) = > { MessageBox.Show(“Button clicked!”); }; }