Explaining Delegates in C#

In my previous post, I spoke about a few very basic and simple reasons of using delegates - primarily callback. In this post, I'll talk about creating Events using delegates.

I have tried to annotate the class with comments so that it is easy to comprehend. But IMHO, the best way to figure out what's going on is to copy/paste the following code and create breakpoint in the Main() class and hit F11 to step into the code. You will notice that Events are based on the Observer or Publish/Subscribe design pattern.

There are 3 rules which are MANDATORY when you are planning to create events...

Rule 1> The delegate must be defined with two arguments
Rule 2> These arguments always represent TWO objects… 
            The Publisher (object that raised the event)
            Event Information object
Rule 3> The 2nd object HAS to be derived from EventArgs

Step through the code and see for yourself how easy this is!!

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

namespace DelegatesAndEvents
{
    //There are 3 rules which are MANDATORY when you are planning to create events
    //Rule 1> The delegate must be defined with two arguments
    //Rule 2> These arguments always represent TWO objects… 
    //          The Publisher (object that raised the event)
    //          Event Information object
    //Rule 3> The 2nd object HAS to be derived from EventArgs

    //To comply with Rule 3 we create a LoggerEventArgs which is derived from EventArgs
    class LoggerEventArgs : EventArgs
    {
        //constructor to initialize the UserName property
        public LoggerEventArgs(string UserName)
        {
            this.username = UserName;
        }

        string username;
        public string UserName
        {
            get { return username; }
        }
    };

    //To comply with Rule 1 and 2, in the publisher class we created a delegate and event declaration
    class InventoryManager // Publisher
    {
        public delegate void LoggerEventHandler(object source, LoggerEventArgs e);
        public event LoggerEventHandler OnInventoryUpdate;

        //This method will fire an event called OnInventoryUpdate whenever called
        public void LogEvent(string username)
        {
            LoggerEventArgs e = new LoggerEventArgs(username);
            if (OnInventoryUpdate != null)
            {
                Console.WriteLine("LogEvent > Raising events to all subscribers...
");
                OnInventoryUpdate(this, e);
            }
        }
    };

    class InventoryLogger // Subscriber
    {
        InventoryManager inventoryManager;
        public InventoryLogger(InventoryManager inventoryManager)
        {
            Console.WriteLine("InventoryWatcher > Subscribing to OnInventoryUpdate event...
");
            this.inventoryManager = inventoryManager;

            //Wiring the event so that the event is fired
            inventoryManager.OnInventoryUpdate += 
                    new InventoryManager.LoggerEventHandler(OnInventoryUpdate);
        }

        void OnInventoryUpdate(object source, LoggerEventArgs e)
        {
            Console.WriteLine("The guy who changed this inventory was... " + e.UserName);
        }
    }

    class DelegateEvents
    {
        public static void Main()
        {
            InventoryManager inventoryManager = new InventoryManager();

            Console.WriteLine("Main > Instantiating the subscriber... 

");
            InventoryLogger inventoryLog = new InventoryLogger(inventoryManager);

            inventoryManager.LogEvent("Rahul Soni");
            Console.ReadLine();
        }
    };
}

In the next post, I will talk about Asynchronous callbacks using delegates.

转: http://www.dotnetscraps.com/dotnetscraps/post/Explaining-Delegates-in-C-Part-2-(Events).aspx

原文地址:https://www.cnblogs.com/shuaixf/p/3319157.html