C# delegate and event usage example

When using a delegate, you must first instantiate it. Just like a class, use the new keyword to generate a new instance of the delegate, and then associate one or more methods that match the delegate signature with the delegate instance. When the delegate is subsequently called, all methods associated with the delegate instance will be called.
The association with the delegate can be a method in any class or structure, and can be a static method, as long as it is an accessible method.

1. Create a delegate type using the keyword delegate (delegate)


    public delegate void DelegateChangeStart(string str);//创建一个实例
    public class Program
    {
    
    
        #region 定义方法
        static void TestWriteLine1(string str)
        {
    
    
            Console.WriteLine("这里是方法一:{0}", str);
        }
        static void TestWriteLine2(string str)
        {
    
    
            Console.WriteLine("这里是方法二:{0}", str);
        }
        static void TestWriteLine3(string str)
        {
    
    
            Console.WriteLine("这里是方法三:{0}", str);
        }
        #endregion
        static void Main(string[] args)
        {
    
    
            DelegateChangeStart EventChargeStartPan1, EventChargeStartPan2, EventChargeStartPan3;//定义委托变量

            //实现委托
            EventChargeStartPan1 = TestWriteLine1;
            EventChargeStartPan2 = TestWriteLine2;
            EventChargeStartPan3 = TestWriteLine3;

            //调用委托
            EventChargeStartPan1("1");
            EventChargeStartPan1("2");
            EventChargeStartPan1("3");

            Console.WriteLine("****************结束****************");


            Console.ReadLine();
        }
    }

Insert picture description here
2. A delegate instance can be associated with multiple methods:


    public delegate void DelegateChangeStart(string str);//创建一个实例
    public class Program
    {
    
    
        #region 定义方法
        static void TestWriteLine1(string str)
        {
    
    
            Console.WriteLine("这里是方法一:{0}", str);
        }
        static void TestWriteLine2(string str)
        {
    
    
            Console.WriteLine("这里是方法二:{0}", str);
        }
        static void TestWriteLine3(string str)
        {
    
    
            Console.WriteLine("这里是方法三:{0}", str);
        }
        #endregion
        static void Main(string[] args)
        {
    
    
            //DelegateChangeStart EventChargeStartPan1, EventChargeStartPan2, EventChargeStartPan3;//定义委托变量

            实现委托
            //EventChargeStartPan1 = TestWriteLine1;
            //EventChargeStartPan2 = TestWriteLine2;
            //EventChargeStartPan3 = TestWriteLine3;

            调用委托
            //EventChargeStartPan1("1");
            //EventChargeStartPan1("2");
            //EventChargeStartPan1("3");

            Console.WriteLine("****************结束****************");


            DelegateChangeStart EventChargeStartPan4;//定义委托变量

            EventChargeStartPan4 = TestWriteLine1;
            EventChargeStartPan4 += TestWriteLine2;
            EventChargeStartPan4 += TestWriteLine3;
            EventChargeStartPan4("四");

            Console.WriteLine("****************结束****************");

            Console.ReadLine();
        }
    }

Insert picture description here

3. Use "-" to remove a method in a delegate instance


    public delegate void DelegateChangeStart(string str);//创建一个实例
    public class Program
    {
    
    
        #region 定义方法
        static void TestWriteLine1(string str)
        {
    
    
            Console.WriteLine("这里是方法一:{0}", str);
        }
        static void TestWriteLine2(string str)
        {
    
    
            Console.WriteLine("这里是方法二:{0}", str);
        }
        static void TestWriteLine3(string str)
        {
    
    
            Console.WriteLine("这里是方法三:{0}", str);
        }
        #endregion
        static void Main(string[] args)
        {
    
    
            //DelegateChangeStart EventChargeStartPan1, EventChargeStartPan2, EventChargeStartPan3;//定义委托变量

            实现委托
            //EventChargeStartPan1 = TestWriteLine1;
            //EventChargeStartPan2 = TestWriteLine2;
            //EventChargeStartPan3 = TestWriteLine3;

            调用委托
            //EventChargeStartPan1("1");
            //EventChargeStartPan1("2");
            //EventChargeStartPan1("3");

            //Console.WriteLine("****************结束****************");


            DelegateChangeStart EventChargeStartPan4;//定义委托变量

            EventChargeStartPan4 = TestWriteLine1;
            EventChargeStartPan4 += TestWriteLine2;
            EventChargeStartPan4 += TestWriteLine3;
            EventChargeStartPan4("四");

            Console.WriteLine("****************结束****************");
            EventChargeStartPan4 -= TestWriteLine2;
            EventChargeStartPan4("减后的四");

            Console.ReadLine();
        }
    }

Insert picture description here
Where EventChargeStartPan4 = TestWriteLine1; use "=" instead of "+=", because EventChargeStartPan4 was not instantiated before, you can use the following code;
but if you use the following method, a compilation error will occur: "DelegateChangeStart" method does not use "0" Overload of three parameters;
reference: http://www.tracefact.net/tech/009.html

Pass the method as a parameter

Delegates can allow methods to be passed to other methods as parameters:


    public delegate void DelegateChangeStart(string str);//创建一个实例
    public class Program
    {
    
    
        #region 定义方法
        static void TestWriteLine1(string str)
        {
    
    
            Console.WriteLine("这里是方法一:{0}", str);
        }
        static void TestWriteLine2(string str)
        {
    
    
            Console.WriteLine("这里是方法二:{0}", str);
        }
        static void TestWriteLine3(string str)
        {
    
    
            Console.WriteLine("这里是方法三:{0}", str);
        }
        #endregion

        static void Test(DelegateChangeStart str)
        {
    
    
            if (str != null)
            {
    
    
                str("5");
            }
        }
        static void Main(string[] args)
        {
    
    
            
            DelegateChangeStart EventChargeStartPan4= TestWriteLine1;//定义委托变量

            EventChargeStartPan4 = TestWriteLine1;
            EventChargeStartPan4 += TestWriteLine2;
            EventChargeStartPan4 += TestWriteLine3;
            EventChargeStartPan4("四");

            Console.WriteLine("****************结束****************");
            DelegateChangeStart EventChargeStartPan5 = TestWriteLine1;//定义委托变量实现
            Test(EventChargeStartPan5);
            EventChargeStartPan5("五");

            Console.ReadLine();
        }
    }

Insert picture description here

event

The event itself is a delegate type . Since the delegate can bind and call multiple methods, it will bring convenience to event handling. The type only needs to expose the event to the outside, and it can be associated with other places outside, so that the event subscription needs to be declared in the class ( but whether it is declared as public or not, it is always declared as private. In addition, it has two Two methods are add_MakeGreet and remove_MakeGreet. These two methods are used to register the delegate type method and cancel the registration . In fact, it is: "+=" corresponds to add_MakeGreet, "-=" corresponds to remove_MakeGreet. And these two methods are Access restrictions depend on the access limiter when the event is declared.)

1. First define the delegate used as the event encapsulation type, and use the event keyword to declare the event.
2. In order to allow the derived class to rewrite the code that triggers the event, a protected method is usually declared in the class, which is customarily named On<event name>


    public class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            
            PotInfo potinfo = new PotInfo();
            potinfo.EventChargeStartPan += Potinfo_EventChargeStartPan;//在输入+=后面按teb键就会自动生成一个事件处理的方法函数
            Console.WriteLine("按下任意键开始执行循环");

            Console.ReadLine();
            potinfo.Start();//开始执行

            Console.ReadLine();
        }

        private static void Potinfo_EventChargeStartPan()
        {
    
    
            Console.WriteLine("{0}  按下空格键", DateTime.Now.ToString());//按下事件显示当前时间文字输出
        }
    }


    public delegate void DelegateChangeStartHelper();//定义委托
    public class PotInfo
    {
    
    
        //声明事件
        public event DelegateChangeStartHelper EventChargeStartPan;
        protected virtual void OnEventChargeStartPan()
        {
    
    
            if (this.EventChargeStartPan != null)
            {
    
    
                EventChargeStartPan();
            }
        }

        public void Start()
        {
    
    
            while (true)
            {
    
    
                ConsoleKeyInfo keyinfo = Console.ReadKey();//读取键值
                if (keyinfo.Key == ConsoleKey.Spacebar)//按下空格键触发
                {
    
    
                    OnEventChargeStartPan();
                }
                if (keyinfo.Key == ConsoleKey.Escape)//按下esc键退出
                {
    
    
                    Console.WriteLine("{0}按下esc退出", DateTime.Now.ToString());
                    break;
                }
            }
        }
    }

Insert picture description here
DelegateHelper class parameters
If a corresponding delegate is defined for different events, once the number increases, it is difficult to manage. To solve this problem, the .NET class library provides an event handling delegate with generic parameters.

public Action<string> EventSweepCode;
        public void SweepCode(string value)
        {
    
    
            EventSweepCode(value);
        }

Action<data type> The parameter type of the method encapsulated by this delegate. This type of parameter is contravariant. That is, you can use the specified type or a less derived type. For more information about covariance and contravariance, see Covariance and contravariance in Generics.

public class DelegateHelper
    {
    
    
        public static DelegateHelper GetDelegateHelper;

        public static DelegateHelper Instance
        {
    
    
            get
            {
    
    
                if (null == GetDelegateHelper)
                {
    
    
                    GetDelegateHelper = new DelegateHelper();

                }
                return GetDelegateHelper;
            }
        }


        public Action<string> EventSweepCode;
        public void SweepCode(string value)
        {
    
    
        	if(EventSweepCode!=null){
    
    
            	EventSweepCode(value);
        	}
        }
    }
    
    public class Program
    {
    
    
        static void Main(string[] args)
        {
    
    

            DelegateHelper.Instance.EventSweepCode += Potinfo_EventChargeStartPan;//在输入+=后面按teb键就会自动生成一个事件处理的方法函数
            Console.WriteLine("输入任意值开始执行循环");
            Console.ReadLine();
            Console.WriteLine("开始执行");
            PotInfo potinfo = new PotInfo();
            potinfo.Start();//开始执行

            Console.ReadLine();
        }

        private static void Potinfo_EventChargeStartPan(string value)
        {
    
    
            Console.WriteLine("{0}  按下空格键", value.ToString());//按下事件显示当前时间文字输出
        }
    }

    public class PotInfo
    {
    
    
        public void Start()
        {
    
    
            while (true)
            {
    
    
                ConsoleKeyInfo keyinfo = Console.ReadKey();//读取键值
                if (keyinfo.Key == ConsoleKey.Spacebar)//按下空格键触发
                {
    
    
                    DelegateHelper.Instance.SweepCode(DateTime.Now.ToString());
                }
                if (keyinfo.Key == ConsoleKey.Escape)//按下esc键退出
                {
    
    
                    Console.WriteLine("{0}按下esc退出", DateTime.Now.ToString());
                    break;
                }
            }
        }
    }

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_37192571/article/details/109055503