代码1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace 事件1
{
internal class Program
{
static void Main(string[] args)
{
Timer timer =new Timer();//事件拥有者
timer.Interval = 1000;
Boy boy =new Boy();//事件响应者
timer.Elapsed += boy.Action;//订阅//Elapsed--事件
timer.Start();
Console.ReadKey();
}
}
class Boy
{
internal void Action(object sender, ElapsedEventArgs e)//事件处理
{
Console.WriteLine("JUMP");
}
}
}
运行程序:一秒打印一次 "JUMP"
------------------------- ----------------------- -------------------------
代码2
添加引用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 事件2
{
internal class Program
{
static void Main(string[] args)
{
Form form=new Form();//事件拥有者
Controller controller=new Controller(form);//事件响应者
form.ShowDialog();
}
}
class Controller
{
private Form form;//Forms类型的字段
public Controller(Form form)//构造函数
{
if (form != null)
{
this .form = form;
this.form.Click += this.FormClick;//订阅//form.Click--事件
}
}
private void FormClick(object sender, EventArgs e)
{
this.form.Text = DateTime.Now.ToString();//事件处理
}
}
}
运行结果:点击窗口---弹出时间显示