C#事件
关键点是搞清楚下面几个概念和他们之间的关系
事件模型的五个组成部分
-
事件的拥有者(event source,对象)
-
事件成员(event, 成员)
-
事件的响应者(event subscriber,对象)
-
事件处理器(event hander, 成员) — 本质上是一个回调方法
-
事件订阅—把事件处理器与事件关联在一起,本质上是一种以委托类型为基础的“约定”
事件发布和响应者分开的情况
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";
}
一个事件可以同时挂接多个事件处理器。
一个事件处理器也可以同时被多个事件挂接。