Code
class 含参事件测试
{
//6.现在来触发事件
static void Main(string[] args)
{
Dog dog = new Dog();
Host host = new Host(dog);
//当前时间:从2009年11月1日23:59:50开始计时
DateTime now = new DateTime(2009,11,1,23,59,50);
DateTime midnight = new DateTime(2009,11,2,0,0,0);
//等待午夜的到来
Console.WriteLine("时间一秒一秒地流逝……");
while(now<midnight)
{
Console.WriteLine("当前时间:"+now);
Thread.Sleep(1000);
now = now.AddSeconds(1);
}
//午夜零点小偷到达,小狗发出警报事件
Console.WriteLine("\n月黑风高的午夜\n");
Console.WriteLine("小偷进入了房间……");
AlarmEventArgs e = new AlarmEventArgs(3);
dog.OnAlarm(e);
}
}
//构造事件参数
public class AlarmEventArgs : EventArgs
{
public int numberOfThieves;
public AlarmEventArgs(int numberValue)
{
this.numberOfThieves = numberValue;
}
}
//事件发送者
class Dog
{
//1.声明关于事件的委托
public delegate void AlarmEventHandler(object sender,AlarmEventArgs e);
//2.声明事件
public event AlarmEventHandler Alarm;
//3.编写引发事件的函数
public void OnAlarm(AlarmEventArgs e)
{
if (this.Alarm != null)
{
Console.WriteLine("\n小狗:有小偷进来了,汪汪……\n");
this.Alarm(this,e);
}
}
}
//事件接收者
class Host
{
//4.编写事件处理程序,参数中包含着numberOfThieves信息
//如果只有一个小偷,则抓住小偷;如果多于一个,主人报警
void HostHandleAlarm(object sender, AlarmEventArgs e)
{
if (e.numberOfThieves <= 1)
{
Console.WriteLine("主人:抓住小偷!");
}
else
{
Console.WriteLine("主人:我家来了{0}个小偷,快报警!",e.numberOfThieves);
}
}
//5.注册事件处理程序
public Host(Dog dog)
{
dog.Alarm+=new Dog.AlarmEventHandler(HostHandleAlarm);
}
}
class 含参事件测试
{
//6.现在来触发事件
static void Main(string[] args)
{
Dog dog = new Dog();
Host host = new Host(dog);
//当前时间:从2009年11月1日23:59:50开始计时
DateTime now = new DateTime(2009,11,1,23,59,50);
DateTime midnight = new DateTime(2009,11,2,0,0,0);
//等待午夜的到来
Console.WriteLine("时间一秒一秒地流逝……");
while(now<midnight)
{
Console.WriteLine("当前时间:"+now);
Thread.Sleep(1000);
now = now.AddSeconds(1);
}
//午夜零点小偷到达,小狗发出警报事件
Console.WriteLine("\n月黑风高的午夜\n");
Console.WriteLine("小偷进入了房间……");
AlarmEventArgs e = new AlarmEventArgs(3);
dog.OnAlarm(e);
}
}
//构造事件参数
public class AlarmEventArgs : EventArgs
{
public int numberOfThieves;
public AlarmEventArgs(int numberValue)
{
this.numberOfThieves = numberValue;
}
}
//事件发送者
class Dog
{
//1.声明关于事件的委托
public delegate void AlarmEventHandler(object sender,AlarmEventArgs e);
//2.声明事件
public event AlarmEventHandler Alarm;
//3.编写引发事件的函数
public void OnAlarm(AlarmEventArgs e)
{
if (this.Alarm != null)
{
Console.WriteLine("\n小狗:有小偷进来了,汪汪……\n");
this.Alarm(this,e);
}
}
}
//事件接收者
class Host
{
//4.编写事件处理程序,参数中包含着numberOfThieves信息
//如果只有一个小偷,则抓住小偷;如果多于一个,主人报警
void HostHandleAlarm(object sender, AlarmEventArgs e)
{
if (e.numberOfThieves <= 1)
{
Console.WriteLine("主人:抓住小偷!");
}
else
{
Console.WriteLine("主人:我家来了{0}个小偷,快报警!",e.numberOfThieves);
}
}
//5.注册事件处理程序
public Host(Dog dog)
{
dog.Alarm+=new Dog.AlarmEventHandler(HostHandleAlarm);
}
}