C#委托-多播委托

一、发布/订阅 观察者模式

  • 实现过程
    使用接口和委托两种方式实现,委托使用多播委托

  • 使用event关键字
    event关键来约束调用着不能外部调用,并且强制了委托链只能使用(+= -= )操作符,增加了代码的健壮性

namespace Demo02
{
    /* interface PaperObjcet
   {

       public void SetNewsPaper(NewsPaper newsPaper);
       public void ReaderPaper();
   }*/


    class Company //:PaperObjcet
    {
        public string Name { set; get; }

        public Company(string name)
        {
            this.Name = name;
        }

        public NewsPaper newsPaper = new NewsPaper();

        //订阅方法
        public void ReaderPaper()
        {
            Console.WriteLine("订阅者:{0},报纸title:{1},报纸content:{2}"
                , this.Name, this.newsPaper.Title, this.newsPaper.Content);
        }

        public void SetNewsPaper(NewsPaper newsPaper)
        {
            this.newsPaper = newsPaper;
        }
    }

    class Person //:PaperObjcet
    {
        public string Name { set; get; }

        public Person(string name)
        {
            this.Name = name;
        }

        public NewsPaper newsPaper = new NewsPaper();

        //订阅方法
        public void ReaderPaper()
        {
            Console.WriteLine("订阅者:{0},报纸title:{1},报纸content:{2},出版社{3}:"
                , this.Name, this.newsPaper.Title, this.newsPaper.Content, this.newsPaper.PublishName);
        }

        public void SetNewsPaper(object sender, pubilsherArge arg)
        {
            if (sender is Pubilsher1)
            {
                arg.newsPaper.PublishName = (sender as Pubilsher1).Name;
            }

            if (sender is Pubilsher2)
            {
                //newsPaper.PublishName = (sender as Pubilsher2).Name;
            }

            this.newsPaper = arg.newsPaper;
        }
    }

    class pubilsherArge : System.EventArgs
    {

        public pubilsherArge(NewsPaper newsPaper)
        {
            this.newsPaper = newsPaper;
        }

        public NewsPaper newsPaper { get; set; }
    }

    class Pubilsher2
    {

    }

    class Pubilsher1
    {
        public string Name { get; set; }

        public Pubilsher1(string name)
        {
            this.Name = name;
        }

        //public List<PaperObjcet> Subscribers = new List<PaperObjcet>();

        //声明委托
        //public delegate void Subscribers(NewsPaper newsPaper);

        //public Subscribers subscribers { get; set; }

        //event来进行约束 只能使用内部内的方式来调用方法,强制使用提示+= -= 等等 event上下文关键字 and remove
        //public event Action<object, pubilsherArge> Subscribers;
        public event EventHandler<pubilsherArge> Subscribers = null;

        /*
         * 委托空处理
         * 委托链异常等处理
         * ref out 非void等的处理方式
         */
        public void SendNewsPaper(NewsPaper newsPaper)
        {
            newsPaper.PublishName = Name;

            if (Subscribers != null)
            {
                //异常处理,委托链
                try
                {
                    foreach (Action<object, pubilsherArge> handler in Subscribers.GetInvocationList())
                    {
                        handler(this, new pubilsherArge(newsPaper));
                    }
                }catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }

            /* Subscribers.ForEach(person =>
             {
                 person.SetNewsPaper(newsPaper);
             });*/

            //Subscribers(newsPaper); 会出现空异常
        }


    }

    class NewsPaper
    {
        public string PublishName { set; get; }
        public string Content { set; get; }
        public string Title { set; get; }

    }
    class ObserverDemo
    {       /*
             * 包容类 外部类
             */
        Person person = new Person("a");
        Person person1 = new Person("b");

        Pubilsher1 pubilsher = new Pubilsher1("XX出版社");
            
        pubilsher.Subscribers += person.SetNewsPaper;
            //pubilsher.Subscribers.Add(person);
            //pubilsher.Subscribers.Add(person1);

            pubilsher.SendNewsPaper(new NewsPaper()
            {
            Title = "标题",
                Content = "内容"
            }) ;

            person.ReaderPaper();
         
    }
}

二、lombda表达式

   public void Test(){
 		var list = new List<int>() { 1, 5, 4, 8, 7, 1, 5, 4, 6 };

            int sum = 0;
            list.ForEach(n =>{

                Console.WriteLine(n);

            });

            var order =  list.Sum(n =>{
                 if (n % 2 == 0)
                     return sum + n;
                 return sum;
             });
             Console.WriteLine(order);

            var iList =  list.Find( n => n >1);
            Console.WriteLine(iList);

            var iList = list.FindAll(n => n > 1);
            iList.ForEach(n => {
                Console.WriteLine(n);
            });

        }

三、 delegate委托

 //delegate委托
        //delegate bool Function(int num);
        /*
         * 使用lombd表达式
         */

        static Func<int, bool> GreaterThan10 = delegate (int n)
        {
            return n >= 10;
        };

        static Func<int, bool> IsEven = delegate (int n)
        {
            return n % 2 == 0;
        };



        static List<T> Traverse<T>(List<T> nums, Func<int, bool> function)
        {

            List<T> list = new List<T>();

            foreach (dynamic num in nums)
            {
                if (function(num)) //num % 2 ==0 num >= 10
                {
                    list.Add(num);
                }
            }

            return list;

        }
 enum Compare
    {
        max,
        min
    }
    class DelegationDemo
    {

        static T getMaxAndMin<T>(List<T> t, Compare resultType) where T : struct
        {
            T max = t[0];

            foreach (dynamic num in t)
            {
                switch (resultType)
                {
                    case Compare.max:
                        if (num > max)
                        {
                            max = num;
                        }
                        break;
                    case Compare.min:
                        if (num < max)
                        {
                            max = num;
                        }
                        break;
                    default:
                        Console.WriteLine(" 暂不支持!。。。");
                        break;
                }
            }
            return max;
        }

这里方法传递的Func有程序提供的方法,使用委托完成,委托一对一一个方法对应用一个委托,一对一的含义,调用时具体传递具体方法即可,多播委托表一个对应多个方法,一对多关系

发布了16 篇原创文章 · 获赞 3 · 访问量 309

猜你喜欢

转载自blog.csdn.net/weixin_41963220/article/details/103309600