C#:事件
事件:事件是对象发送的消息,发送信号通知客户发生了操作。这个操作可能是由鼠标单击引起的,也可能是由某些其他的程序逻辑触发的。事件的发送方不需要知道哪个对象或者方法接收它引发的事件,发送方只需知道它和接收方之间的中介(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 }