C# events and delegates

namespace Contacts
{
    //Define the delegate, which defines the type of methods that can be represented
    public delegate void GreetingDelegate(string name);

    //新建的GreetingManager类
    public class GreetingManager
    {
        public event GreetingDelegate delegate1;
        public void GreetPeople(string name)
        {
            delegate1(name);
           
        }
    }

    class Program1
    {
        private static void EnglishGreeting(string name)
        {
            MessageBox.Show("Morning, " + name);
        }

        private static void ChineseGreeting(string name)
        {
            MessageBox.Show("早上好, " + name);
        }

        public static void RK()
        {
            GreetingManager gm = new GreetingManager();
            gm.delegate1 += EnglishGreeting;
            gm.delegate1 += ChineseGreeting;
            gm.GreetPeople("菠萝粥");
        }
    }
}

Summary: I have been troubled by events and commissions for a long time, and I have no patience to read them every time. I have been reading and writing questions for a while, and I finished reading this chapter with patience. /www.tracefact.net/tech/009.html Zhang Ziyang's sharing gave me a preliminary understanding of the knowledge points, but I don't know when to use delegation, hahaha

One: Delegate

1. The delegate is also a class, so just declare it under the namespace, use the keyword delegate to declare the delegate, such as

public delegate void GreetingDelegate(string name);

The return value and parameters of the delegate need to be the same as the parameters according to the bound method.

2. Create a delegate type variable, GreetingDelegate delegate1; Bind the delegate method to the delegate,

delegate1 = EnglishGreeting;

delegate1 += ChineseGreeting;

The first "=" is equivalent to instantiating a delegate, "+=" is a binding method, or direct GreetingDelegate delegate1 = new GreetingDelegate(EnglishGreeting); delegate1 += ChineseGreeting;

3. Call the delegate: delegate("pineapple porridge"), the delegate is to pass the method as a parameter, and then directly use the delegate to change the face.

 

Two: the event

1. Delegates understand, events are much easier, create events of delegate type variables, public event GreetingDelegate delegate1;

delegate1 += EnglishGreeting;delegate1 += ChineseGreeting;

When using events, you can use "+=" or "-=". Events are equivalent to encapsulating delegate type variables, which are used in the same way as delegate variables.

 

three:

1. The names of the delegate types should all end with EventHandler.

2. The event is named Event End.

 

 

-------------------------------------------------- Conforms to the spec. .net spec instance ---------------------------------

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

namespace Delegate
{
    // Water heater
    public class Heater
    {
        private int temperature;
        public string type = "RealFire 001"; // Add model as demo
        public string area = "China Xian"; // Add origin as demo
        // declare delegate
        public delegate void BoiledEventHandler(Object sender, BoiledEventArgs e);
        public event BoiledEventHandler Boiled; //declare the event

        // Define the BoiledEventArgs class and pass the information that the Observer is interested in
        public class BoiledEventArgs : EventArgs
        {
            public readonly int temperature;
            public BoiledEventArgs(int temperature)
            {
                this.temperature = temperature;
            }
        }

        // Can be overridden by classes that inherit from Heater, so that the inheriting class refuses to monitor it by other objects
        protected virtual void OnBoiled(BoiledEventArgs e)
        {
            if (Boiled != null)
            { // If an object registers
                Boiled(this, e ); // call the methods of all registered objects
            }
        }

        // Boil water.
        public void BoilWater()
        {
            for (int i = 0; i <= 100; i++)
            {
                temperature = i;
                if (temperature > 95)
                {
                    //Create a BoiledEventArgs object.
                    BoiledEventArgs e = new BoiledEventArgs(temperature);
                    OnBoiled(e); // call the OnBolied method
                }
            }
        }
    }

    // Alarm
    public class Alarm
    {
        public void MakeAlert(Object sender, Heater.BoiledEventArgs e)
        {
            Heater heater = (Heater)sender; //Is this familiar?
            //Access the public field in sender
            Console.WriteLine("Alarm: {0} - {1}: ", heater.area, heater.type);
            Console.WriteLine("Alarm: beep, water has {0} Temperature: ", e.temperature);
            Console.WriteLine();
        }
    }

    // Display
    public class Display
    {
        public static void ShowMsg(Object sender, Heater.BoiledEventArgs e)
        { //Static method
            Heater heater = (Heater)sender;
            Console.WriteLine("Display: {0} - {1}: ", heater.area, heater.type);
            Console.WriteLine("Display: The water is about to boil, the current temperature: {0} degrees.", e.temperature);
            Console.WriteLine();
        }
    }

    class Program
    {
        static void Main()
        {
            Heater heater = new Heater();
            Alarm alarm = new Alarm();

            heater.Boiled += alarm.MakeAlert; //Register method
            heater.Boiled += (new Alarm()).MakeAlert; //Register method for anonymous object
            heater.Boiled += new Heater.BoiledEventHandler(alarm.MakeAlert); / /You can also register
            heater.Boiled += Display.ShowMsg; //Register static methods

            heater.BoilWater(); //Boil water, the method of the registered object will be called automatically
        }
    }
}

  1. The parameter of the Object type in the delegate declaration prototype represents the Subject, which is the monitoring object, in this case the Heater (water heater). The callback function (such as MakeAlert of Alarm) can access the object (Heater) that triggered the event through it.
  2. The EventArgs object contains the data that the Observer is interested in, in this case temperature.

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325776560&siteId=291194637