asp.net中c#自定义事件的实现方法详解

2019-05-23 06:05:34于海丽

            Console.WriteLine("~~~~~~~~~时间开始走啊走啊~~~~~~~~~");
            while(now <nigth){
                Console.WriteLine("当前时间:"+now);
                System.Threading.Thread.Sleep(1000);
                now = now.AddSeconds(1);
            }
            Console.WriteLine("~~~~~~~我是小偷,我来了~~~~~~~~~~~~");
            dog.OnAlarn();
        }
    }
    class Dog {
        //第一步:声明关于事件的委托
        public delegate void AlarnEven(object sender,EventArgs e);
        //第二步:声明事件
        public event AlarnEven Alarn;
        //第三步:编写引发事件的函数
        public void OnAlarn() {
            if(this.Alarn!=null){
                Console.WriteLine("n狗报警:有小偷进来了.汪汪汪~~~~~~~~~");
                this.Alarn(this,new EventArgs());
            }
        }
    }
    class Host {
        //第四:编写事件的处理程序
        void HostAlarn(object sender, EventArgs e)
        { Console.WriteLine("主人:抓住小偷啦..!"); }
        //第五步:注册事件的处理程序
        public Host(Dog dog) {
            dog.Alarn += new Dog.AlarnEven(HostAlarn);
        }
    }
}

希望本文所述对大家的asp.net程序设计有所帮助。