初始事件
定义
单词Event,翻译为“事件”
通俗的解释为:能够发生的什么事情
角色
使对象或类具备通知能力的成员
- 事件是一种使对象或类能够提供通知的成员
使用
用于对象或类间动作的协调与信息传递(消息推送)
原理
事件模型(event model)中的两个“5”
- “发生-响应”中的5个部分——闹钟响了你起床、孩子饿了你做饭(订阅关系)
- “发生-响应”中的5个动作——处理事件
提示
- 事件多用于桌面、手机等开发的客户端编程,因为这些程序经常是用户通过事件来“驱动”的
- 各种编程语言对这个机制的实现方法不尽相同
- Java语言里没有事件这种成员,也没有委托这种类型。Java的“事件”是使用接口来实现的
- MVC、MVP、MVVM等模式,是事件模式更高级、更有效的“玩法”
- 日常开发的时候,使用已有事件的机会比较多,自己声明事件的机会比较少,所以先学使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
namespace 事件
{
class Program
{
static void Main(string[] args)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000;
Boy boy = new Boy();
timer.Elapsed += boy.Action; //自动生成事件处理器,事件订阅(+=)
timer.Start();
Console.ReadLine();
}
}
class Boy
{
internal void Action(object sender, ElapsedEventArgs e)
{
Console.WriteLine("Here!");
}
}
}
事件的应用
实例演示
派生(继承)与扩展(extends)
事件模型的五个组成部分
- 事件的拥有者(event source,对象)
- 事件的成员(event,成员)
- 事件的响应者(event subscriber,对象)
- 事件处理器(event handler,对象)——本质上是一个回调方法
- 事件订阅——把事件处理器与事件关联在一起,本质上是一种以委托类型为基础的“约定”
注意
- 事件处理器的方法成员
- 挂接事件处理器的时候,可以使用委托实例,也可以直接使用方法名,这个就是“语法糖”
- 事件处理器对事件的订阅不是随意的,匹配与否由声明事件时所使用的的委托类型来检测
- 事件可以同步调用也可以异步调用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 事件的应用
{
class Program
{
static void Main(string[] args)
{
Form form = new Form();
Control control = new Control(form);
form.ShowDialog();
}
}
class Control
{
private Form form;
public Control(Form form)
{
if (form!=null)
{
this.form = form;
this.form.Click += this.FormedClicked; //Alt+enter可以生成对应的事件
}
}
private void FormedClicked(object sender, EventArgs e)
{
this.form.Text = DateTime.Now.ToString();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 窗口
{
//非可视化编程
class Program
{
static void Main(string[] args)
{
MyForm myForm = new MyForm();
myForm.ShowDialog();
}
}
class MyForm:Form
{
private TextBox textBox;
private Button button;
public MyForm()
{
this.button = new Button();
this.textBox = new TextBox();
this.Controls.Add(this.button); //添加显示按钮
this.Controls.Add(this.textBox);
this.button.Click += this.ButtonClicked;//事件
this.button.Text = "Click Me";
this.button.Top = 100;
}
private void ButtonClicked(object sender, EventArgs e)
{
this.textBox.Text = "Hello World!!(哎呀,其实我被盖住了)";
}
}
}