Delegates exist because sometimes we need to take a function as an argument to another function, so we use a Delegate mechanism

A delegate is declared with the keyword delegate, which actually defines a “function type” that specifies the type of the function’s arguments and return value. (that is, a delegate with no arguments and no return value can only accept methods with no arguments and no return value, and vice versa.)

The.NET compiler rigorously checks for a match between the type of the function and the type not made, and only if it does, can the converted delegate instance be passed as an argument to the calling function.

You can use delegates to make your program more generic by taking functions as arguments. Delegates are declared with the keyword delegate. In fact, creating a delegate is equivalent to creating a class that is derived from System. Delegates are a type-safe approach compared to c++ function Pointers.

Small cases:

using System;
delegate int NumberChanger(int n);  // Define the delegate
namespace DelegateAppl
{
   class TestDelegate
   {
      static int num = 10;
      public static int AddNum(int p)
      {
         num += p;
         return num;
      }
      public static int MultNum(int q)
      {
         num *= q;
         return num;
      }
      public static int getNum()
      {
         return num;
      }
      static void Main(string[] args)
      {
         // Create a delegate instance
         NumberChanger nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);
         // Use the delegate object to call the method
         nc1(25);
         Console.WriteLine("Nc1 is: {0}", getNum());
         nc2(5);
         Console.WriteLine("Nc2 is: {0}", getNum()); Console.ReadKey(); }}}Copy the code

Multicast Delegate: We call a Muiticast Delegate a Delegate that contains multiple functions. All the references to the delegated functions are stored in the call list of the multicast Delegate class. When the multicast Delegate is called, all the functions in the list are called in order.

The syntax for registering a function to a multicast delegate is:

Register a function with a multicast delegate via the += operator

Syntax for removing a function from a multicast delegate: Use the -= operator,,

Note: A multicast delegate must return void,,,


C# Event

An Event, “Event,” is basically a user action, such as a button, click, mouse movement, and so on, or some occurrence, such as a system-generated notification. The application needs to respond to events as they occur. For example, interrupt. Events are used for interprocess communication.

Use delegates through events

Events are declared and generated in classes, and are associated with event handlers by using delegates from the same class or another class. The class containing the event is used to publish the event. This is called the Publisher class. Other classes that receive the event are called subscriber classes. Events use a publisher-subscriber model.

A Publisher is an object that contains the event and delegate definitions. The relationship between events and delegates is also defined in this object. Objects of the Publisher class call this event and notify other objects.

A subscriber is an object that receives an event and provides an event handler. Delegates in the Publisher class call methods (event handlers) in the Subscriber class.

Declare an Event

To declare an event inside a class, you must first declare the delegate type of the event. Such as:

public delegate void JianCe(int wendu);
Copy the code

Then, declare the event itself, using the event keyword:

Public event JianCe Show;Copy the code

Water heater boil water example:

using System;
using System.Threading;


/* Suppose we have a high-end water heater. When the water temperature exceeds 95 degrees, the speaker will start to speak to tell you the temperature of the water. The LCD screen will also change the water temperature display to indicate that the water is about to boil. An improvement on the above procedure: assume that the water heater consists of three parts: the water heater, which is only responsible for boiling the water alarm, the alarm display, the display prompt, and the water temperature */
namespace_1_1_1 Delegate event brief {// Define the delegate to detect the water temperature (temperature)
    public delegate void JianCe(int WenDu);

        / / water heater
        class Heater
        {
            // Define the event to detect the water temperature
            public static event JianCe Show;
            public static event JianCe Hear;

            public Heater(int _warm)
            {
                warm = _warm;
            }

            static int warm = 27; // The initial temperature of water

            public void ShaoShui()
            {
                for (int i = 0; i < 100; i++)
                {
                     Thread.Sleep(1000);
                     warm++;
                    if (warm < 99)   // After a while, the temperature increases
                    {                     
                       if(Show ! =null)  // Reduce the coupling{ Show(warm); }}else // Alarm,
                     {
                         //if (Show ! = null) { Show(warm); }
                         // The same as the above code, simplified writingHear? .Invoke(warm); }}}}class Alert   / / alarm
        {
            public void BaoJing(int warm)
            {
                if (warm > 95 )
                {
                    Console.WriteLine("The alarm reminds me..."); }}}class Monitor  / / display
        {
            public void XianShi(int warm)
            {
                if (warm < 100)
                {
                    Console.WriteLine("Current water temperature is {0} and heating.", warm); }}}class Program
        {

            static void Main(string[] args)
            {
                Console.WriteLine("Input water temperature, start boiling water:");
                int warm = int.Parse(Console.ReadLine());
                Heater heater = new Heater(warm);
                Alert alert = new Alert();
                Monitor monitor = new Monitor();

                // Register the eventHeater.Show += monitor.XianShi; Heater.Hear += alert.BaoJing; heater.ShaoShui(); Heater.Show -= monitor.XianShi; Heater.Hear -= alert.BaoJing; Console.ReadKey(); }}}Copy the code

The operation result is as shown in the figure above. The alarm is always reported when the water reaches a certain temperature.