Understanding events and event handlers in C#

后端 未结 12 1522
野性不改
野性不改 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:52

    My understanding of the events is;

    Delegate:

    A variable to hold reference to method / methods to be executed. This makes it possible to pass around methods like a variable.

    Steps for creating and calling the event:

    1. The event is an instance of a delegate

    2. Since an event is an instance of a delegate, then we have to first define the delegate.

    3. Assign the method / methods to be executed when the event is fired (Calling the delegate)

    4. Fire the event (Call the delegate)

    Example:

    using System;
    
    namespace test{
        class MyTestApp{
            //The Event Handler declaration
            public delegate void EventHandler();
    
            //The Event declaration
            public event EventHandler MyHandler;
    
            //The method to call
            public void Hello(){
                Console.WriteLine("Hello World of events!");
            }
    
            public static void Main(){
                MyTestApp TestApp = new MyTestApp();
    
                //Assign the method to be called when the event is fired
                TestApp.MyHandler = new EventHandler(TestApp.Hello);
    
                //Firing the event
                if (TestApp.MyHandler != null){
                    TestApp.MyHandler();
                }
            }
    
        }   
    
    }
    

提交回复
热议问题