2012-10-09 25 views

回答

8

您可以使用lambda表达式构建一个可以附加到事件的匿名方法。

例如,如果你犯了一个Windows窗体与ButtonLabel,你可以添加,在构造函数(InitializeComponent()后):

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

这将导致标签更改为按钮点击。

+0

烨被重写。我也想指出有关添加和删除匿名事件处理程序:http://stackoverflow.com/questions/2051357/c-sharp-adding-and-removing-anonymous-event-handler – devshorts

+0

@devshorts是的。如果您还需要取消订阅,这不一定很好。 –

+0

单语句方法体不是大括号吗? – Superbest

0

尝试这个例子

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!”); 
}; 
}