C#事件

C#事件

关键点是搞清楚下面几个概念和他们之间的关系

事件模型的五个组成部分

  1. 事件的拥有者(event source,对象)

  2. 事件成员(event, 成员)

  3. 事件的响应者(event subscriber,对象)

  4. 事件处理器(event hander, 成员) — 本质上是一个回调方法

  5. 事件订阅—把事件处理器与事件关联在一起,本质上是一种以委托类型为基础的“约定”

在这里插入图片描述

事件发布和响应者分开的情况
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
///事件发布和响应者分开的情况
namespace EventExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Timer timer = new Timer();//事件发布者
            timer.Interval = 1000;
            Boy boy = new Boy();//事件响应者
            Gril gril = new Gril();
            timer.Elapsed += boy.Action;//事件订阅
            timer.Elapsed += gril.Action;
            timer.Start();
            Console.ReadLine();
        }
    }

    class Boy
    {
        internal void Action(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("Jump");
        }
    }

    class Gril
    {
        internal void Action(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("Sing");
        }
    }
}

事件的响应者响应自己的字段成员的事件的情况
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
///三星例子
///事件的响应者响应自己的字段成员的事件的情况
namespace EventExample_3Star
{
    class Program
    {
        static void Main(string[] args)
        {
            MyForm form = new MyForm();
            form.ShowDialog();
        }
    }

    class MyForm : Form
    {
        private TextBox textBox;
        private Button button;

        public MyForm()
        {
            this.textBox = new TextBox();
            this.button = new Button();
            this.Controls.Add(this.button);
            this.Controls.Add(this.textBox);
            this.button.Click += this.ButtonClicked;
            this.button.Text = "Say Hello";
            this.button.Top = 100;
        }

        private void ButtonClicked(object sender, EventArgs e)
        {
            this.textBox.Text = "Hello word!!!!!!!!!!!!!";
        }
    }
}

事件处理函数里面的sender参数是为了区分事件的触发者是谁

第二种挂接事件处理器的方法
this.button3.Click += new EventHandler(this.ButtonClicked);
已经废弃的挂接方式
this.button3.Click += delegate(object sender, EventArgs e{
this.textBox1.Text = "haha";
})
现在比较流行的一种方法
this.button3.Click += ( sender,  e) => {
    this.textBox1.Text = "Hoho";
}

一个事件可以同时挂接多个事件处理器。
一个事件处理器也可以同时被多个事件挂接。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值