Understanding events and event handlers in C#

后端 未结 12 1699
野性不改
野性不改 2020-11-22 04:06

I understand the purpose of events, especially within the context of creating user interfaces. I think this is the prototype for creating an event:

public vo         


        
12条回答
  •  野的像风
    2020-11-22 04:29

    I agree with KE50 except that I view the 'event' keyword as an alias for 'ActionCollection' since the event holds a collection of actions to be performed (ie. the delegate).

    using System;
    
    namespace test{
    
    class MyTestApp{
        //The Event Handler declaration
        public delegate void EventAction();
    
        //The Event Action Collection 
        //Equivalent to 
        //  public List EventActions=new List();
        //        
        public event EventAction EventActions;
    
        //An Action
        public void Hello(){
            Console.WriteLine("Hello World of events!");
        }
        //Another Action
        public void Goodbye(){
            Console.WriteLine("Goodbye Cruel World of events!");
        }
    
        public static void Main(){
            MyTestApp TestApp = new MyTestApp();
    
            //Add actions to the collection
            TestApp.EventActions += TestApp.Hello;
            TestApp.EventActions += TestApp.Goodbye;
    
            //Invoke all event actions
            if (TestApp.EventActions!= null){
                //this peculiar syntax hides the invoke 
                TestApp.EventActions();
                //using the 'ActionCollection' idea:
                // foreach(EventAction action in TestApp.EventActions)
                //     action.Invoke();
            }
        }
    
    }   
    
    }
    

提交回复
热议问题