A simple example of C # delegates and events

Entrust

C # where is my understanding that this commission can be seen as a type of template method . (But did not find the relevant understand
such as have several return values, the same type of method parameter list, you can use the same template type to represent, then instantiate a delegate type to bind one or more methods, then this method is called once more, which is equivalent to the method of the object?.

using System;
namespace test { 
    class Test{
        static void fun1(int a) {
            Console.WriteLine("fun one {0}",a);
        }
        static void fun2(int a)
        {
            Console.WriteLine("fun two {0}", a);
        }
        static void fun3(int a)
        {
            Console.WriteLine("fun three {0}", a);
        }
        
        //定义一个委托类型
        public delegate void fun(int b);
        static void Main(string[] args)
        {
            fun a, b, c, d,e;
            //绑定方法
            a = fun1;
            b = fun2;
            c = fun3;
            d = fun1;
            d += fun2;
            d += fun3;
            e = new fun(fun1);
            //调用方法
            a(1);
            b(2);
            c(3);
            d(4);
            d -= fun2;
            d(4);
            e(2);
            Console.ReadKey();
        }
    }
}

event

Events need to use the commission, or a special delegate.
In fact, the more events than entrust a key event, entrusted a protective effect, with the event, external calls can not be entrusted directly to the inside of the publisher, because it is unreasonable, when publishers released this function should be commissioned by the publisher own decisions.

using System;
namespace test {
    /***********发布器类***********/
    public class EventTest
    {
        public delegate void NumManipulationHandler(); //声明委托
        public NumManipulationHandler ChangeNum; //声明事件

        public void OpenDoor()
        {
            ChangeNum();  //事件触发
        }
    }

    /***********订阅器类***********/
    public class subscribEvent
    {
        public void printf()
        {
            Console.WriteLine("The door is opened.");
        }
    }

    /***********触发***********/
    public class MainClass
    {
        public static void Main()
        {
            EventTest e = new EventTest(); /* 实例化事件触发对象 */
            subscribEvent v = new subscribEvent(); /* 实例化订阅事件对象 */

            /* 订阅器的printf()在事件触发对象中注册到委托事件中 */
            e.ChangeNum += new EventTest.NumManipulationHandler(v.printf);
            e.OpenDoor(); /* 触发了事件 */
            e.ChangeNum();
            Console.ReadKey();
        }
    }
}

Guess you like

Origin www.cnblogs.com/zxcoder/p/12497941.html