// 高手就没必要看了,小弟只是自学 , 如果你不腻赐教,小弟感激不尽!
创建一个事件驱动的程序需要的基本步骤:
1、申明关于事件的委托
2、申明事件
3、编写引发事件的函数
4、创建事件处理程序
5、注册事件处理程序
6、在适当的条件下出发事件
实例 : 主人与看门狗 当晚上主人睡觉时,看门狗负责看家,如果有小偷进来,看门狗发出一个事件Alarm,主人接收到Alarm事件后就会采取相应的行动;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 自定义事件
{
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog();
Host host = new Host(dog);
DateTime now=new DateTime(2014,3,27,23,59,50);
DateTime midnight=new DateTime(2014,3,28,0,0,0);
Console.WriteLine("时间一分一秒的流逝");
while(now<midnight)
{
Console.WriteLine("当前时间:"+now);
System.Threading.Thread.Sleep(1000);
now = now.AddSeconds(1);
}
Console.WriteLine("黑夜:"+now+"小偷来了");
dog.OnAlarm();
Console.ReadKey();
}
}
class Dog
{
//申明关于事件的委托
public delegate void AlarmEventHandler(object sender, EventArgs e);
//申明事件
public event AlarmEventHandler Alarm;
//编写引发事件的函数
public void OnAlarm()
{
if(this.Alarm != null)
{
Console.WriteLine("狗叫,小偷来了");
this.Alarm(this, new EventArgs());
}
}
}
class Host
{
//编写事件处理程序
void HostHandlerAlram(object sender, EventArgs e)
{
Console.WriteLine("主人,抓住了小偷!");
}
//注册事件处理程序
public Host(Dog dog)
{
dog.Alarm += new Dog.AlarmEventHandler(HostHandlerAlram);
}
}
}
事件的继承
下面的代码是对上面代码的更改
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 自定义事件继承
{
public class AlarmEventArgs : EventArgs//事件的继承
{
public int numberOfthieves;
public AlarmEventArgs(int numberOfthieves)
{
this.numberOfthieves = numberOfthieves;
}
}
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog();
Host host = new Host(dog);
DateTime now = new DateTime(2014, 3, 27, 23, 59, 50);
DateTime midnight = new DateTime(2014, 3, 28, 0, 0, 0);
Console.WriteLine("时间一分一秒的流逝");
while(now < midnight)
{
Console.WriteLine("当前时间:" + now);
System.Threading.Thread.Sleep(1000);
now = now.AddSeconds(1);
}
Console.WriteLine("黑夜:" + now + "小偷来了");
AlarmEventArgs e = new AlarmEventArgs(2);
dog.OnAlarm(e);
Console.ReadKey();
}
}
class Dog
{
//申明关于事件的委托
public delegate void AlarmEventHandler(object sender, AlarmEventArgs e);
//申明事件
public event AlarmEventHandler Alarm;
//编写引发事件的函数
public void OnAlarm(AlarmEventArgs e)
{
if(this.Alarm != null)
{
Console.WriteLine("狗叫,小偷来了");
this.Alarm(this, e);
}
}
}
class Host
{
//编写事件处理程序
void HostHandlerAlram(object sender, AlarmEventArgs e)
{
if(e.numberOfthieves <= 1)
{
Console.WriteLine("主人,抓住了小偷");
}
else
{
Console.WriteLine("主人拨打了 110 , 我家来了{0}个小偷",e.numberOfthieves);
}
}
//注册事件处理程序
public Host(Dog dog)
{
dog.Alarm += new Dog.AlarmEventHandler(HostHandlerAlram);
}
}
}