1.事件模型:
①A有一个事件,一群人关心A的该事件
②A的该事件发生了
③关心该事件的人被依次通知
④被通知的人根据事件信息(事件参数)来用事件处理器(本质是一个回调方法)响应(处理事件)
P.S.java的事件是通过接口来实现的
事件模式高阶:MVC、MVP、MVVM
在timer类里,就包含事件,属性和方法:
闪电:事件
方块:方法
钳子:属性
2.以下是建立一个boy对timer的某一事件响应的实例:
class Program
{
static void Main(string[] args)
{
Timer timer = new Timer();
timer.Interval = 1000;//每过一秒触发一次
Boy boy = new Boy();
timer.Elapsed += boy.Action;//代表boy订阅这个事件;
timer.Start();
Console.ReadLine();
}
}
class Boy
{
//事件处理器:Action方法
internal void Action(object sender, ElapsedEventArgs e)
{
Console.WriteLine("JUMP");
}
}
3.以下是一个自定义窗体,对click事件作出响应:
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);
//事件:click 事件响应者:myform的实例
this.button.Click += this.ButtonClicked;//建立订阅关系,myform实例对click作出响应;
this.button.Text = "click me";
this.button.Top = 100;
}
//事件处理器
private void ButtonClicked(object sender, EventArgs e)
{
this.textBox.Text = "hello everyone";
}
输出结果:
4.用wpf可视化编程:建立事件
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.button1.Click += Button1_Click; //订阅
}
private void Button1_Click(object sender, EventArgs e)
{
this.textBox1.Text = "Hello Everyone";
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
输出结果: