事件的应用
-
实例演示
- 派生(继承)与扩展(extends)
-
事件模型的五个组成部分
- 1.事件的拥有者(event source,对象)T周
- 2.事件成员(event,成员)
- 3.事件的响应者(event subscriber,对象)
- 4.事件处理器(event handler,成员)——本质上是一个回调方法
- 5.事件订阅——把事件处理器与事件关联在一起,本质上是一种以委托类型为基础的约定”
-
注意
- 事件处理器是方法成员
- 挂接事件处理器的时候,可以使用委托实例,也可以直接使用方法名这是个“语法糖。
- 事件处理器对事件的订阅不是随意的,匹配与否由声明事件时所使用的委托类型来检事件可以同步调用也可以异步调用
简单的例子:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Timers; namespace demo2 { public delegate double Calc(double x, double y); 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 demo2 { public delegate double Calc(double x, double y); 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) { this.Form = form; this.Form.Click += this.FormClicked;//订阅 Click事件成员 } 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 demo2 { public delegate double Calc(double x, double y); class Program { static void Main(string[] args) { MyForm form = new MyForm(); form.Click += form.FormClicked; form.ShowDialog(); } } class MyForm : Form { internal void FormClicked(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 demo2 { public delegate double Calc(double x, double y); 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 = 30; } private void buttonClicked(object sender, EventArgs e) { this.textBox.Text = "Hello World!!!!!!!!!!!!!!!!!"; } } }
???