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