2012-10-09 27 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!」); 
}; 
}