• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C#:事件

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#中String.Join()方法发布时间:2022-07-10
下一篇:
C#中使用反射的优缺点发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap