C#之事件
3.事件
class Dog
{
//声明关于事件的委托
public delegate void AlarmEventHandler(object sender, EventArgs e);
//声明事件
public event AlarmEventHandler Alarm;
//触发事件的函数
public void OnAlarm()
{
if (this.Alarm != null)
{
Console.WriteLine("\n有小偷进来了,汪汪......");
this.Alarm(this,new EventArgs());
}
}
}
class Host
{
//事件处理函数
void HostHandleAlarm(object sender, EventArgs e)
{
Console.WriteLine("主人:抓住了小偷!");
}
//注册事件处理函数
public Host(Dog dog)
{
dog.Alarm += new Dog.AlarmEventHandler(HostHandleAlarm);
}
}
//触发事件
class Program
{
public static void Main(string[] args)
{
Dog dog = new Dog();
Host host = new Host(dog);
DateTime now = new DateTime(2002, 12, 31, 23, 59, 50);
DateTime midnight = new DateTime(2003, 1, 1, 0, 0, 0);
Console.WriteLine("时间一点点的流逝.........");
while (now < midnight)
{
Console.WriteLine("当前的时间为:{0}", now);
System.Threading.Thread.Sleep(1000);
now=now.AddSeconds(1);
}
Console.WriteLine("\n小偷摸进了主人家中," + now);
dog.OnAlarm();
Console.ReadKey();
}
}
4.事件
public class NumberOfThiefEventArgs : EventArgs
{
public int numberofthief;
public NumberOfThiefEventArgs(int number)
{
numberofthief = number;
}
}
class Dog
{
public delegate void AlarmEventHandler(object sender, NumberOfThiefEventArgs e);
public AlarmEventHandler Alarm;
public void OnAlarm(NumberOfThiefEventArgs e)
{
if(Alarm!=null)
{
Console.WriteLine("咱们家里招贼了!!!");
this.Alarm(this,e);
}
}
}
class Host
{
public void HostHandleAlarm(object sender, NumberOfThiefEventArgs e)
{
if (e.numberofthief <= 1)
{
Console.WriteLine("咱们家里来了很少的贼,不用怕,已经抓住了");
}
else
{
Console.WriteLine("家里来了{0}个贼,打电话报警吧!",e.numberofthief);
}
}
public Host(Dog dog)
{
dog.Alarm += new Dog.AlarmEventHandler(HostHandleAlarm);
}
}
class Program
{
public static void Main(string[] args)
{
Dog dog = new Dog();
Host host = new Host(dog);
DateTime now = new DateTime(2016, 1, 1);
DateTime midmonth = new DateTime(2016, 1, 15);
Console.WriteLine("时间一点点的流逝");
while (now < midmonth)
{
Console.WriteLine("现在是时间:"+now);
System.Threading.Thread.Sleep(2000);
now = now.AddDays(2);
}
Console.WriteLine("时间 "+now+" 小偷进门了");
//NumberOfThiefEventArgs e = new NumberOfThiefEventArgs(3);
NumberOfThiefEventArgs e = new NumberOfThiefEventArgs(1);
dog.OnAlarm(e);
Console.ReadKey();
}
}