天天看点

C#事件处理 与委托

C#事件处理 与委托

using system;  

using system.collections.generic;  

using system.text;  

namespace 事件处理  

{  

    // declare the delegate handler for the event:  

    public delegate void myeventhandler();  

    class testevent  

    {  

        // declare the event implemented by myeventhandler.  

        public event myeventhandler triggerit;  

        // declare a method that triggers the event:  

        public void trigger()  

        {  

            triggerit();  

        }  

        // declare the methods that will be associated with the triggerit event.  

        public void mymethod1()  

            system.console.writeline("hello!");  

        public void mymethod2()  

            system.console.writeline("hello again!");  

        public void mymethod3()  

            system.console.writeline("good-bye!");  

        static void main()  

            // create an instance of the testevent class.  

            testevent myevent = new testevent();  

            // subscribe to the event by associating the handlers with the events:  

            myevent.triggerit += new myeventhandler(myevent.mymethod1);  

            myevent.triggerit += new myeventhandler(myevent.mymethod2);  

            myevent.triggerit += new myeventhandler(myevent.mymethod3);  

            // trigger the event:  

            myevent.trigger();  

            // unsuscribe from the the event by removing the handler from the event:  

            myevent.triggerit -= new myeventhandler(myevent.mymethod2);  

            system.console.writeline("\"hello again!\" unsubscribed from the event.");  

            // trigger the new event:  

            console.readkey();  

    }  

}  

C#事件处理 与委托

输出内容如下:  

C#事件处理 与委托

hello!  

hello again!  

good-bye!  

"hello again!" unsubscribed from the event.  

good-bye!