事件
事件模型的五个组成部分
1.事件的拥有者
2.事件成员
3.事件的响应者
4.事件处理器——本质上是一个回调方法
5.事件订阅——吧事件处理器与事件关联在一起,本质上是一种以委托类型为基础的“约定”
- 事件处理器是方法成员
- 挂接事件处理器的时候,可以使用委托实例,也可以直接使用方法名,这是个“语法糖”
- 事件处理器对事件的订阅不是随意的,匹配与否由声明事件时所使用的委托类型来检测
- 事件可以同步调用也可以异步调用
小闪电即为事件。
//事件的简单运用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace 事件
{
internal class Program
{
static void Main(string[] args)
{
Timer timer = new Timer();
timer.Interval = 1000;
Boy boy = new Boy();
Girl girl = new Girl();
timer.Elapsed += boy.Action;
timer.Elapsed += girl.Action;
timer.Start();
Console.ReadLine();
}
}
class Boy
{
internal void Action(object sender, ElapsedEventArgs e)
{
Console.WriteLine("jump!");
}
}
class Girl
{
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 事件二
{
internal class Program
{
static void Main(string[] args)
{
Form form = new Form();
Controller controller = new Controller(form);
form.ShowDialog();
}
}
class Controller
{
private Form form;
public Controller(Form form)
{
if(form != null)
{
this.form = form;
this.form.Click += this.FormClicked;
}
}
private void FormClicked(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 事件二
{
internal class Program
{
static void Main(string[] args)
{
MyForm form = new MyForm();
form.Click += form.Formclickd;
form.ShowDialog();
}
}
class MyForm : Form
{
internal void Formclickd(object sender, EventArgs e)
{
this.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 事件三
{
internal 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;
}
private void ButtonClicked(object sender, EventArgs e)
{
this.textBox.Text = "EHllo,World!!!!!!!!";
}
}
}