委托

委托关键字:delegate

*多播委托调用如果有带返回值只会返回最后一个,基本多播委托不带返回值

--用于约束方法返回值、类型   描述方法

    public class TestDelegate : System.MulticastDelegate//委托继承自System.MulticastDelegate类,约束方法的模版,可不使用
    {
        //...
    }

1.创建委托

            public delegate void TestHandler()//无参

           {//......
                   };
            public delegate void TestHandler(int x, int y)//有参

           {//.......
                   };

2.委托实例化

TestHandler testHandler = new TestHandler(show);//1 
TestHandler testHandler = show;//2 show为方法名
TestHandler testHandler = () => {};//lambad方式实例化

3.委托调用

testHandler.Invoke();//第一种调用方式
testHandler();//第二种调用方式
testHandler.BeginInvoke(null, null);//多播委托不能异步调用

4.多播委托

 public void Index()
        {
            TestHandler testHandler = new TestHandler(show);
            {
               //+=  -=委托操作符,形成一串方法列表
                testHandler += show1;//符合TestHandler委托的多个方法
                testHandler += show;
                testHandler += show1;
                testHandler -= show1;
                testHandler += () =>{};

                testHandler();//执行
            }
        }

一个完整的代码

    public delegate void PlusHandlerTop<T>(T x, T y);
    public delegate void Nothing();//委托的声明
    public delegate void OnePara(long lPara);
    public delegate string StringReturn(long lPara);

    public class DelegateShowClass
    {public static void Show()
        {
            //三种实例化的方式 
            Nothing nothing1 = new Nothing(DoNothing);
            Nothing nothing2 = DoNothing;
            Nothing nothing3 = () =>
            {
                Console.WriteLine("这里已经进入了 nothing3");
                Thread.Sleep(1000);
                Console.WriteLine("这里已经结束了 nothing3");

            };

            //+=  -=操作符
            nothing1 += DoNothing;
            nothing1 += DoNothing;
            nothing1 += nothing2;
            nothing1 += () => { Console.WriteLine("cccc"); };
            nothing1 += () => { Console.WriteLine("cccc"); };
            nothing1 -= () => { Console.WriteLine("cccc"); };
            nothing1 -= DoNothing;

            try
            {
                //委托的调用
                nothing1();
            }
            catch
            {

            }
            nothing1.Invoke();//委托的另外一种调用方式

            nothing3.BeginInvoke(null, null);

            //nothing1.BeginInvoke(null, null);//多播委托不能异步调用
            foreach (Nothing method in nothing1.GetInvocationList())
            {
                method.BeginInvoke(null, null);
            }



            Console.WriteLine("委托调用结束");

        }



        private static void DoNothing()
        { }
原文地址:https://www.cnblogs.com/JarvisNote/p/5056996.html