c#委托的声明、实例化和调用

  // 1 委托的声明、实例化和调用
  // 2 委托的意义:解耦   

class Program
    {
        static void Main(string[] args)
        {
            MyDelegateEvent delegateEvent = new MyDelegateEvent();
            delegateEvent.Show();

            Student student = new Student();
            student.SayHi();

            Console.ReadKey();
        }
    }

    // 1.委托本质就是个类
    // 2.继承自System.MulticastDelegate 特殊类-不能被继承
    class MyDelegateEvent
    {
        //1. 委托声明
        public delegate void NoReturnNopara();
        public delegate void NoReturnWithPara(int x, int y);
        public delegate MyDelegateEvent WithReturnWithPara(out int x, ref int y);
        public void Show()
        {
            //2.委托的实例化 要求传递一个参数类型 返回值类型跟委托一致
            NoReturnNopara method = new NoReturnNopara(this.DoNothing);
            //WithReturnWithPara withPara = new WithReturnWithPara(this.ParaReturn);
            //int y = 3;
            //withPara.Invoke(out int x,ref y);
            //3.委托实例的调用
            method.Invoke();
            method();//也可以省略掉.Invoke()
            IAsyncResult asyncResult = method.BeginInvoke(null, null); //启动一个线程完成计算
            //method.EndInvoke(asyncResult);//等待异步调用结束
        }
        public void DoNothing()
        {
            Console.WriteLine("this is DoNothing");
        }

        private MyDelegateEvent ParaReturn(out int x, ref int y)
        {
            throw new Exception();
        }
    }
 
    class Student
    {

  public delegate void SayHiDelegate(string name);
        //自上往下 逻辑解耦 ,方便升级维护
        //自下往上 代码重用,去掉重复代码
        public void SayHi()
        {
            SayHiPerfact("王大师", this.China);

            SayHiPerfact("Tom Hiddleston", this.Britain);

            SayHiPerfact("蒼井そら", Japan);
        }

        /// <summary>
        /// 相同的东西用一个方法实现,不同的各自去写,然后通过委托组合
        /// </summary>
        /// <param name="name"></param>
        /// <param name="method"></param>
        public void SayHiPerfact(string name, SayHiDelegate method)
        {
            Console.WriteLine("我是通用方法");//这里可以写通用方法 比如写日志,加异常处理
            method.Invoke(name);              //执行不同逻辑
        }

        public void China(string name)
        {
            Console.WriteLine($"{name},早上好");
        }
        public void Britain(string name)
        {
            Console.WriteLine($"{name},Good morning");
        }
        public void Japan(string name)
        {
            Console.WriteLine($"{name},おはよう");
        }
    }

 

 

posted @ 2019-10-25 14:49  王大师123  阅读(1875)  评论(0编辑  收藏  举报