c # case




1. The concept of events

Events are used as informers of messages, which are convenient and quick to write. A clear boundary is drawn between the modules, which improves the maintainability and reusability of the application.
In the vernacular, it means that "something" happens, and then the event is used as the informer to store what happened, and then send it to multiple observers who need to respond.
This person who has never done it is not
easy to understand: to make an analogy: there are a group of thieves, there are thieves, snitches, etc., and I am a watchman, so I am the so-called "incident". As a very good watchman. I want to store the situation after "something happened" into corresponding black words according to the type of thieves in advance. For example, for the snitch, I want to store it-"escape from the roof", for the thief, I want to store it-"slide through the back door" etc. Slang. At this time "something" happened-"the master came back" or "the police came", I would inform the snatch to "run away from the roof" and inform the snatch to "slee through the back door"...
I suggest the host take a look at the observer mode , The event actually encapsulates the observer pattern at the bottom. In the above example, the guard is the informer, the thief is the observer, and the owner and the police are the observers. The event is to respond differently according to the situation, and send a series of different or the same notification (message) to the class as the "observer".

In the past when we wrote such programs, we often used a waiting mechanism. In order to wait for something to happen, we needed to constantly detect certain judgment variables. After the introduction of event programming, this process was greatly simplified:





2. Places to pay attention to the incident:

  1. Declared in the class.
  2. The publisher is a class, and the subscriber is a class.
  3. You can use +=and -=add or remove delegate.

Publisher and subscriber patterns:

Publisher: Defines a series of events that may be of interest to other parts. Other classes can "register" to get notified.

Subscriber: When an event occurs, the publisher "triggers the event" and then executes all events submitted by the subscriber.



3. Examples

1. The first event example

namespace VsCore_Demo {
    
    

    public delegate void SaySomething (string name);
    class Program {
    
    
        public void SayHello (string name) {
    
    
            Console.WriteLine ("Hello," + name + "!");
        }
        public void SayNiceToMeetYou (string name) {
    
    
            Console.WriteLine ("Nice to meet you," + name + "!");
        }

        public event SaySomething come;
        public event SaySomething come2;



        public void test () {
    
    

            //声明两个委托.
            //声明委托的时候,传进去的参数是方法名。
            SaySomething sayhello = new SaySomething (SayHello);
            SaySomething saynice = new SaySomething (SayNiceToMeetYou);

            //把两个委托添加到事件里
            come += sayhello;
            come += saynice;

            //事件发生了。
            //触发事件是用事件直接加参数。
            come ("张三");
            System.Console.WriteLine("***********");
        }



        static void Main (string[] args) {
    
    
            Program program = new Program ();
            program.test ();
            Console.Read ();
        }
    }
}

The event declaration is like this:

 public event SaySomething come;

This shows that the come event only deals with the delegate SaySomething . When an event occurs, these delegates are called by the event , and then the specific implementation method is called by the delegate .

To instantiate the delegate, note that we use the new keyword, just like instantiating a class, and then pass in a parameter, but this parameter is not a string type or an int type, but a method name.

            SaySomething sayhello = new SaySomething (SayHello);
            SaySomething saynice = new SaySomething (SayNiceToMeetYou);

Let's go back and look at the definition of "event":
public event SaySomething come;

The name of the "delegation" has been pointed out here, so we can directly add the method to the event, and omit the instantiation process of the "delegation", so the above test() method can be simply written as:

public void test()
 {
    
          
 come += SayHello;    
        come += SayNiceToMeetYou;   
        come("张三"); 
 }

When stimulating the commission, I went back to abstraction, and just passed the parameters in. It didn't matter what process was in the middle.

Commission + event is a typical example of the observer pattern. The so-called commission is actually the observer, it will care about a certain event, once this event is triggered, the observer will act

2. Event completion: classic interview questions for meowing, waking up, and mouse running

The specific code is as follows:
There are a few points to note:

  • CatCall? .Invoke(); Invoke the event;
  • Event += can be translated as. Meowing caused the mouse to run;
using System;

namespace DelegateDemo
{
    
    
    //定义猫叫委托
    public delegate void CatCallEventHandler();
    public class Cat
    {
    
    
        //定义事件
        public event CatCallEventHandler CatCall;
        //定义唤醒事件的方法
        public void OnCatCall()
        {
    
    
            Console.WriteLine("猫叫了一声");
            //唤醒事件。
            CatCall?.Invoke();
        }
    }
    public class Mouse
    {
    
    
        //定义老鼠跑掉方法
        public void MouseRun()
        {
    
    
            Console.WriteLine("老鼠跑了");
        }
    }
    public class People
    {
    
    
        //定义主人醒来方法
        public void WakeUp()
        {
    
    
            Console.WriteLine("主人醒了");
        }
    }

    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            Cat cat = new Cat();
            Mouse m = new Mouse();
            People p = new People();
            //关联绑定 
            cat.CatCall += new CatCallEventHandler(m.MouseRun);
            cat.CatCall += new CatCallEventHandler(p.WakeUp);
            cat.OnCatCall();

            Console.ReadKey();
        }
    }
}

3. Apple's price reduction code:

The standard form of the event is used


    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            Apple ap1 = new Apple()
            {
    
    
                Preice = 5288
            };

            //注册事件
            // 点了 += 以后,可以使用快捷键生成。
            ap1.myEvent += PriceChanged;

            //调整价格,触发事件
            ap1.Preice = 3999;

            Console.ReadKey();
        }


        //事件响应程序
        static void PriceChanged(object sender, MyEventArgs e)
        {
    
    
            Console.WriteLine("年终大促销,iPhone 6 只卖 " + e.NewPrice +" 元, 原价 " + e.OldPrice + " 元,快来抢!"+sender.ToString());
        }
    }


    /// <summary>
    /// 事件参数类
    /// </summary>
    public class MyEventArgs : EventArgs
    {
    
    
        public MyEventArgs(decimal newPrice, decimal oldPrice)
        {
    
    
            this.NewPrice = newPrice;
            this.OldPrice = oldPrice;
        }


        public readonly decimal NewPrice;
        public readonly decimal OldPrice;
    }


    /// <summary>
    /// 事件发布者类
    /// </summary>
    public class Apple
    {
    
    
        private decimal price;


        public decimal Preice
        {
    
    
            get
            {
    
    
                return price;
            }
            set
            {
    
    
                //如果价格变了,触发事件通知用户价格变了
                if (price == value)
                {
    
    
                    return;
                }


                decimal oldPrice = price;
                price = value;

                //调用触发事件的方法。
                //一般激活方法是 On + event
                OnRaiseEvet(new MyEventArgs(price, oldPrice));
            }
        }


        public event EventHandler<MyEventArgs> myEvent;

        //激发方法。
        public virtual void OnRaiseEvet(MyEventArgs e)
        {
    
    

            //如果调用列表不为空,则触发
            if (myEvent != null)
            {
    
    
                myEvent(this, e);

                //event关键字定义的事件只能由事件源对象自己激发,外界无法通过访问委托变量直接激发事件。
                //下面的代码无法编译通过:Publisher p = new Publisher(); p.MyEvent(10);
            }
        }
    }

About the event

  • The main purpose of the event is to prevent interference between subscribers.
  • To declare an event, add event directly in front of the delegate
  • There is a difference between inside and outside : when the event is in the class, it can be used as a delegate, but outside the class, only += and – = operations can be performed
  • Under normal circumstances, the method of activating events is named by On+event by default
  • Activate CatCall? .Invoke()
  • Use eventas a keyword, what is mandatory? (1) Only in the inclusive class, can you send a commission to subscribers, (2) It is not allowed to use = outside the class.
  • sender is used to output the publisher class.
  • For events, the outside can only register itself +=, and cancel itself -=. The outside world cannot cancel other registrants.


reference:

  1. c# Classic Interview Questions—Meow, Master Wake Up, Mouse Run (Processing of Incident)
  2. https://blog.csdn.net/shangrila_ftd/article/details/70148922
  3. Source code for Apple's price cuts
  4. https://zhidao.baidu.com/question/202695971.html

Guess you like

Origin blog.csdn.net/zhaozhao236/article/details/111351541