c#事件处理代码记录

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 自定义事件
{//事件发送者
    class Dog
    {
        //1.声明关于事件的委托;
        public delegate void AlarmEventHandler(object sender, EventArgs e);
        //2.声明事件;
        public event AlarmEventHandler Alarm;
        //3.编写引发事件的函数
        public void OnAlarm()//OnAlarm方法用于触发事件
        {
            if (this.Alarm != null)
                this.Alarm(this, new EventArgs()); //发出警报
        }
    }
    //事件接收者
    class Host
    {
        //5.事件处理程序
        void HostHandleAlarm(object sender, EventArgs e)
        {
            Console.WriteLine("主 人: 抓住了小偷!");
        }

        //4.注册事件处理程序
        public Host(Dog dog) //4.在构造函数中订阅了Dog的Alarm事件。
        {
            dog.Alarm += new Dog.AlarmEventHandler(HostHandleAlarm);
        }
    }
    class Program
    {
        //
        static void Main(string[] args)
        {
            Dog dog = new Dog();
            Host host = new Host(dog);
            DateTime now = new DateTime(2011, 12, 31, 23, 59, 55);
            DateTime midnight = new DateTime(2012, 1, 1, 0, 0, 0);
            Console.WriteLine("时间一秒一秒地流逝,等待午夜的到来... ");
            while (true)
            {
                Console.WriteLine("当前时间: " + now);
                //午夜零点小偷到达,看门狗引发 Alarm 事件
                if (now == midnight)
                {
                    Console.WriteLine("\n 月黑风高的午夜, 小偷悄悄地摸进了主人的屋内...");
                    //引发事件
                    System.Threading.Thread.Sleep(2000); //程序暂停一秒
                    now = now.AddSeconds(2); //时间增加一秒
                    Console.WriteLine("当前时间: " + now);
                    Console.WriteLine("\n 狗报警: 有小偷进来了,汪汪~~~~~~~");
                    System.Threading.Thread.Sleep(2000); //程序暂停2秒
                    now = now.AddSeconds(2); //时间增加一秒
                    dog.OnAlarm();
                   
                    Console.WriteLine("当前时间: " + now);
                    System.Threading.Thread.Sleep(2000); //程序暂停2秒
                    break;
                }
                System.Threading.Thread.Sleep(1000); //程序暂停一秒
                now = now.AddSeconds(1); //时间增加一秒
            }
        }
    }       }










运行结果:

c#事件处理代码记录_第1张图片

你可能感兴趣的:(c#)