委托 Delegate

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyDelegateEvent.Delegate
{



    /// <summary>
    /// 轿车工厂
    /// </summary>
    public class CarFactory
    {

        /// <summary>
        /// 筛选数据
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <param name="source"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public static IEnumerable<TSource> ElevenWhere<TSource>(IEnumerable<TSource> source, Func<TSource, bool> func)
        {
            List<TSource> studentList = new List<TSource>();
            foreach (TSource item in source)
            {
                bool bResult = func.Invoke(item);
                if (bResult)
                {
                    studentList.Add(item);
                }
            }
            return studentList;
        }

        /// <summary>
        /// 通用的异常处理
        /// </summary>
        /// <param name="act">对应任何的逻辑</param>
        public static void SafeInvoke(Action act)
        {
            try
            {
                act.Invoke();
            }
            catch (Exception ex)//按异常类型区分处理
            {
                Console.WriteLine(ex.Message);
            }
        }


        /// <summary>
        /// 生成轿车,
        /// 发动机分三种类型:自然吸气  涡轮增压  电动
        /// 
        /// 传递一个参数给我,然后我来执行不同的逻辑
        /// 传递一个逻辑给我,我去执行
        /// </summary>
        public void BuildCar(BuildEngineDelegate method)
        {

            new List<int>().Where(t => t > 1);

            Console.WriteLine("这里是东风日产乘用车工厂");
            //BuildEngine(engineType);

            //if (engineType == EngineType.NaturalInspiration)
            //{
            //    Console.WriteLine("造一个自然吸气发动机");
            //}
            //else if (engineType == EngineType.Turbo)
            //{
            //    Console.WriteLine("造一个涡轮增压发动机");
            //}
            //else if (engineType == EngineType.Electric)
            //{
            //    Console.WriteLine("造一个电池发动机");
            //}
            method.Invoke();


            Console.WriteLine("造一个外壳");

            Console.WriteLine("造一个底盘");

            Console.WriteLine("造四个轮子");

            Console.WriteLine("组装成一辆车");

            Console.WriteLine("造好了一辆GTR。。");
        }


        public delegate void BuildEngineDelegate();


        public void BuildEngineNaturalInspiration()
        {
            Console.WriteLine("造一个自然吸气发动机");
        }
        public void BuildEngineTurbo()
        {
            Console.WriteLine("造一个涡轮增压发动机");
        }
        public void BuildEngineElectric()
        {
            Console.WriteLine("造一个电池发动机");
        }
        public void BuildEngineFuture()
        {
            Console.WriteLine("造一个光发动机");
        }

        //private void BuildEngine(EngineType engineType)
        //{
        //    if (engineType == EngineType.NaturalInspiration)
        //    {
        //        Console.WriteLine("造一个自然吸气发动机");
        //    }
        //    else if (engineType == EngineType.Turbo)
        //    {
        //        Console.WriteLine("造一个涡轮增压发动机");
        //    }
        //    else if (engineType == EngineType.Electric)
        //    {
        //        Console.WriteLine("造一个电池发动机");
        //    }

        //}
    }

    public enum EngineType
    {
        NaturalInspiration = 0,
        Turbo = 1,
        Electric = 2

    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyDelegateEvent.Event
{
    /// <summary>
    /// 订户
    /// </summary>
    public class Baby
    {
        public void Cry()
        {
            Console.WriteLine("{0} Cry", this.GetType().Name);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyDelegateEvent.Event
{
    public class Brother
    {
        public void Turn()
        {
            Console.WriteLine("{0} Turn", this.GetType().Name);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyDelegateEvent.Event
{
    /// <summary>
    /// 发布者
    /// 一只猫,miao一声
    /// 导致一系列的触发动作
    /// 
    /// 发布者
    /// </summary>
    public class Cat
    {
        public void Miao()
        {
            Console.WriteLine("{0} Miao", this.GetType().Name);
            new Dog().Wang();
            new Mouse().Run();
           
            new Baby().Cry();
            new Mother().Wispher();
            //new Brother().Turn();
            new Father().Roar();
            new Neighbor().Awake();
            new Stealer().Hide();

        }




        public Action MiaoAction;
        public void MiaoDelegate()
        {
            Console.WriteLine("{0} MiaoDelegate", this.GetType().Name);
            if (MiaoAction != null)
                MiaoAction.Invoke();
            //MiaoAction = null;
        }


        //声明一个委托的实例,加上event关键字
        //委托是一种类型,而事件是委托的一个实例,然后加了个event关键字
        //控制了实例的使用权限,更加安全
        public event Action MiaoActionEvent;
        public void MiaoEvent()
        {
            Console.WriteLine("{0} MiaoActionEvent", this.GetType().Name);
            if (MiaoActionEvent != null)
                MiaoActionEvent.Invoke();
            //MiaoActionEvent = null;
        }

    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyDelegateEvent.Event
{
    public class Dog
    {
        public void Wang()
        {
            Console.WriteLine("{0} Wang", this.GetType().Name);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyDelegateEvent.Event
{
    public class Father
    {
        public void Roar()
        {
            Console.WriteLine("{0} Roar", this.GetType().Name);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyDelegateEvent.Event
{
    /// <summary>
    /// 订户
    /// </summary>
    public class Mother
    {
        public void Wispher()
        {
            Console.WriteLine("{0} Wispher", this.GetType().Name);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyDelegateEvent.Event
{
    public class Mouse
    {
        public void Run()
        {
            Console.WriteLine("{0} Run", this.GetType().Name);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyDelegateEvent.Event
{
    public class Neighbor
    {
        public void Awake()
        {
            Console.WriteLine("{0} Awake", this.GetType().Name);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyDelegateEvent.Event
{
    public class Stealer
    {
        public void Hide()
        {
            Console.WriteLine("{0} Hide", this.GetType().Name);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyDelegateEvent
{
    public delegate void NoReturnNoParaOutClass();

    //public class DelegateClass : System.MulticastDelegate
    //{ }

    public class MyDelegate
    {
        public delegate void NoReturnNoPara();
        public delegate void NoReturnWithPara(int x, int y);//1 声明委托
        public delegate int WithReturnNoPara();
        public delegate string WithReturnWithPara(out int x, ref int y);

        public delegate void NoReturnNoParaGeneric<T>();

        public void Show()
        {
            {
                NoReturnWithPara func = (x, y) => { };
                func += (x, y) => Console.WriteLine("123"); ;

                func.Invoke(3, 4);
            }



            //System.MulticastDelegate
            Student student = new Student()
            {
                Id = 96,
                Name = "Summer"
            };
            student.Study();

            //Predicate<int>

            //Func<string>

            {
                NoReturnNoPara method = new NoReturnNoPara(this.DoNothing);//2 委托的实例化


                method.Invoke();//3 委托的调用
                method();

                //method.BeginInvoke(null, null);

                this.DoNothing();

            }

            {
                NoReturnNoPara method = new NoReturnNoPara(this.DoNothing);//当前类的实例方法
                NoReturnNoPara method1 = new NoReturnNoPara(MyDelegate.DoNothingStatic);//当前类的静态方法
                NoReturnNoPara method2 = new NoReturnNoPara(student.Study);//其他类的实例方法
                NoReturnNoPara method3 = new NoReturnNoPara(Student.StudyAdvanced);//其他类的静态方法
            }

            {
                NoReturnNoPara method = new NoReturnNoPara(this.DoNothing);
                method += new NoReturnNoPara(this.DoNothing);
                method += new NoReturnNoPara(MyDelegate.DoNothingStatic);
                method += new NoReturnNoPara(student.Study);
                method += new NoReturnNoPara(Student.StudyAdvanced);

                method += new NoReturnNoPara(new Student().Study);
                method += new NoReturnNoPara(Student.StudyAdvanced);


                method += new NoReturnNoPara(() => Console.WriteLine("这里是lambda表达式"));
                //+=就是把多个方法按顺序排成列表,invoke时按顺序执行
                //method.Invoke();

                method -= new NoReturnNoPara(this.DoNothing);
                method -= new NoReturnNoPara(MyDelegate.DoNothingStatic);
                method -= new NoReturnNoPara(student.Study);

                method -= new NoReturnNoPara(new Student().Study);
                method -= new NoReturnNoPara(Student.StudyAdvanced);

                method -= new NoReturnNoPara(Student.StudyAdvanced);
                method -= new NoReturnNoPara(() => Console.WriteLine("这里是lambda表达式"));
                //-=就是从这个实例上,从后往前挨个匹配,找到第一个完全吻合的移除掉,且只移除一个,找不到不异常
                method.Invoke();


                //method.BeginInvoke(null, null);
                foreach (NoReturnNoPara item in method.GetInvocationList())
                {
                    item.BeginInvoke(null, null);
                }
            }



        }

        private void DoNothing()
        {
            Console.WriteLine("This is DoNothing");
        }
        private static void DoNothingStatic()
        {
            Console.WriteLine("This is DoNothingStatic");
        }

    }
}
using MyDelegateEvent.Delegate;
using MyDelegateEvent.Event;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyDelegateEvent
{
    /// <summary>
    /// 1 委托的声明、实例化和调用
    /// 2 泛型委托--Func Action
    /// 3 委托的意义:解耦
    /// 4 委托的意义:异步多线程
    /// 5 委托的意义:多播委托
    /// 6 事件 观察者模式
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("欢迎来到.net高级班VIP课程,今天是Eleven老师为大家带来的委托事件的学习");
                //MyDelegate myDelegate = new MyDelegate();
                //myDelegate.Show();

                //CarFactory carFactory = new CarFactory();
                ////carFactory.BuildCar(EngineType.NaturalInspiration);
                ////carFactory.BuildCar(EngineType.Turbo);
                ////carFactory.BuildCar(EngineType.Electric);

                //CarFactory.BuildEngineDelegate method = new CarFactory.BuildEngineDelegate
                //(carFactory.BuildEngineNaturalInspiration);

                //carFactory.BuildCar(method);

                //CarFactory.SafeInvoke(() =>
                //    {
                //        carFactory.BuildCar(method);
                //    });

                {
                    Console.WriteLine("************cat.Miao();***********");
                    Cat cat = new Cat();
                    cat.Miao();

                    Console.WriteLine("************cat.MiaoDelegate();***********");
                    cat.MiaoAction += new Dog().Wang;
                    cat.MiaoAction += new Mouse().Run;
                    cat.MiaoAction += new Baby().Cry;
                    cat.MiaoAction += new Mother().Wispher;
                    cat.MiaoAction += new Brother().Turn;
                    cat.MiaoAction += new Father().Roar;
                    cat.MiaoAction += new Neighbor().Awake;
                    cat.MiaoAction += new Stealer().Hide;

                    cat.MiaoAction.Invoke();
                    cat.MiaoAction = null;


                    cat.MiaoAction -= new Stealer().Hide;
                    cat.MiaoDelegate();


                    Console.WriteLine("************cat.MiaoEvent();***********");
                    cat.MiaoActionEvent += new Dog().Wang;//订阅
                    cat.MiaoActionEvent += new Mouse().Run;
                    cat.MiaoActionEvent += new Baby().Cry;
                    cat.MiaoActionEvent += new Mother().Wispher;
                    cat.MiaoActionEvent += new Brother().Turn;
                    cat.MiaoActionEvent += new Father().Roar;
                    cat.MiaoActionEvent += new Neighbor().Awake;

                    //cat.MiaoActionEvent.Invoke();
                    //cat.MiaoActionEvent = null;

                    cat.MiaoAction -= new Stealer().Hide;//取消订阅
                    cat.MiaoActionEvent += new Stealer().Hide;

                    cat.MiaoEvent();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyDelegateEvent
{
    /// <summary>
    /// 
    /// </summary>
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public void Study()
        {
            Console.WriteLine("学习.net高级班公开课");
        }

        public static void StudyAdvanced()
        {
            Console.WriteLine("学习.net高级班vip课");
        }

        public static void Show()
        {
            Console.WriteLine("123");
        }
    }
}
原文地址:https://www.cnblogs.com/zhengqian/p/8556299.html