Using the Event Basics in Unity

illustrate

  Recently, I plan to look back at the basics of C#. After working for a while, I will look back at the basics. There will always be some new understandings.

components of an event

  1. The owner of the event (Source object)
  2. Event members (Event members)
  3. The responder of the event (Event Subscribe object)
  4. Event handler (Event Handle member)本质是一个回调方法
  5. Event subscription: Associating event handlers with events is essentially a "contract" based on the delegate type

The event is divided into the above five components. Generally speaking, the event establishes a connection between two objects through a certain agreement. If the two objects want to respond, they must follow the agreement between the two.

event statement

  • The complete statement
    is written a bit similar to the encapsulation of attributes
namespace CSharpStudy
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            Console.WriteLine("Hello World!");
        }
    }
    //定一个委托类型
    public delegate void StudyEventHandle();

    class Study {
    
    

        private StudyEventHandle studyEventHandle;
        //event关键字修饰
        public event StudyEventHandle StudyEvent {
    
    
            add {
    
    
                this.studyEventHandle += value;
            }
            remove {
    
    
                this.studyEventHandle -= value;
            }
        }
    }
}

confusing questions

The triggering of the event must be triggered by the owner of the event through some operations

Why use the event keyword?

  Events can only appear on the left side of += or -= (只能外部订阅,内部调用), which is why after fully declaring a delegate, it is necessary to use the event keyword to wrap the delegate. If the event is not modified, the program will run normally, but this will make the code unsafe. If it is not modified with the event keyword, we create an instance of New externally, access this delegate through this instance and call it, so that the external can add a response method to it, and can also call it externally, which is obviously not safe.

  The essence of an event is a wrapper for a delegated field. This wrapper restricts the access to the delegated field, which is equivalent to a "mask". Events hide most of the functionality of the delegate instance from the outside, only exposing add/remove. That is mentioned in the previous paragraph 外部订阅,内部调用.

Are events really "delegated fields/instances declared in a special way"?
  No, it just "looks like" when it is declared. The essence of the event is a "mask" added to the entrusted field, which is a wrapper for concealment. Not the delegate field itself.

Why use delegate types to declare events?

  • From the source's point of view, it is to show what messages the source can transmit to the outside world
  • From the subscriber's point of view, it is a convention to constrain what signature method is used to process (response) events
  • An instance of the delegate type will be used to store (reference) the event handler

Comparing Properties and Events

  • Properties are not fields – many times properties are wrappers around fields, this wrapper is used to protect fields from being abused
  • The event is not a delegate field – it is a wrapper around the delegate field, this wrapper is used to protect the delegate field from being abused
  • A wrapper can never be the thing being wrapped

example

The example is also based on what the online teacher said, a situation where a customer goes to a restaurant to order and pay. For a brief analysis, a customer comes to a restaurant and says: The waiter orders! At this moment the waiter came. The customer class is the owner of the event, the waiter tear is the responder of the event, the Action method in the Waiter is the event handler, += associates the customer class and the waiter class together through "agreement".

using System;
using System.Threading;
using System.Timers;

namespace CSharp_Event
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            Console.WriteLine("Hello World!");
         
            Customer customer = new Customer();
            Waiter waiter = new Waiter();
            customer.Order += waiter.Action;
            customer.Action();
            customer.PayTheBill();
        }
    }
   //名字和大小
    public class OrderEventArgs : EventArgs {
    
    
    	//菜名
        public string DishName {
    
     get; set; }
		//大小份
        public string Size {
    
     get; set; }
    }

    public delegate void OrderEventHandle(Customer customer,OrderEventArgs e);
    //顾客类
    public class Customer {
    
    

        private OrderEventHandle orderEventHandle;
        public event OrderEventHandle Order{
    
    

            add {
    
    
                this.orderEventHandle += value;
            }
            remove {
    
    

                this.orderEventHandle -= value;
            }
        }
		//需要支付的价钱
        public double Bill {
    
     get; set; }
		//支付的方法
        public void PayTheBill()
        {
    
    
            Console.WriteLine("请支付"+Bill);
        }

        public void WalkIn() {
    
    
            
            Console.WriteLine("我进到饭店了");
        }

        public void SitDown() {
    
    
            Console.WriteLine("我坐下了");
        }

        public void Tink() {
    
    

            for (int i = 0; i < 5; i++)
            {
    
    
                Console.WriteLine("think");
                Thread.Sleep(1000);
            }

            if (this.orderEventHandle!=null)
            {
    
    
                OrderEventArgs e = new OrderEventArgs();
                e.DishName = "宫保鸡丁";
                e.Size = "large";
                //事件的响应在事件的拥有者中触发
                this.orderEventHandle.Invoke(this, e);
            }
        }

        public void Action()
        {
    
    
            Console.ReadLine();

            WalkIn();

            SitDown();

            Tink();
        }
    }
	//服务类
    public class Waiter
    {
    
    
        public void Action(Customer customer, OrderEventArgs e)
        {
    
    
            Console.WriteLine("我将保存你的点菜:" + e.DishName);
            double price = 10;

            switch(e.Size)
            {
    
    
                case "small":
                    price *= 0.5;
                    break;
                case "large":
                    price *= 1.5f;
                    break;
            }
            customer.Bill += price;
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_44446603/article/details/124549472