事件:事件是對象發送的消息,發送信號通知客戶發生了操作。這個操作可能是由鼠標單擊引起的,也可能是由某些其他的程序邏輯觸發的。事件的發送方不需要知道哪個對象或者方法接收它引發的事件,發送方只需知道它和接收方之間的中介(delegate)。
示例1:
1 using System; 2 using System.Windows.Forms; 3 4 namespace WindowsFormsApplication2 5 { 6 public partial class Form1 : Form 7 { 8 public Form1() 9 { 10 InitializeComponent(); 11 12 // 在引發buttonOne的Click事件時,應執行Button_Click方法,使用+=運算符把新方法添加到委托列表中 13 buttonOne.Click += new EventHandler(Button_Click); 14 buttonTwo.Click += new EventHandler(Button_Click); 15 buttonTwo.Click += new EventHandler(button2_Click); 16 } 17 18 // 委托要求添加到委托列表中的所有方法都必須有相同的簽名 19 private void Button_Click(object sender, EventArgs e) 20 { 21 if (((Button)sender).Name == "buttonOne") 22 { 23 labelInfo.Text = "Button one was pressed."; 24 } 25 else 26 { 27 labelInfo.Text = "Button two was pressed."; 28 } 29 } 30 31 private void button2_Click(object sender, EventArgs e) 32 { 33 MessageBox.Show("This only happens in Button two click event"); 34 } 35 } 36 }
事件處理程序方法有幾個重要的地方:
- 事件處理程序總是返回void,它不能有返回值。
- 只要使用EventHandler委托,參數就應是object和EventArgs。第一個參數是引發事件的對象,在上面的示例中是buttonOne或buttonTwo。第二個參數EventArgs是包含有關事件的其他有用信息的對象;這個參數可以是任意類型,只要它派生自EventArgs即可。
- 方法的命名也應注意,按照約定,事件處理程序應遵循“object_event”的命名約定。
如果使用λ表達式,就不需要Button_Click方法和Button2_Click方法了:
1 using System; 2 using System.Windows.Forms; 3 4 namespace WindowsFormsApplication2 5 { 6 public partial class Form1 : Form 7 { 8 public Form1() 9 { 10 InitializeComponent(); 11 buttonOne.Click += (sender, e) => labelInfo.Text = "Button one was pressed"; 12 buttonTwo.Click += (sender, e) => labelInfo.Text = "Button two was pressed"; 13 buttonTwo.Click += (sender, e) => 14 { 15 MessageBox.Show("This only happens in Button2 click event"); 16 }; 17 } 18 } 19 }
