(精华)2020年8月11日 C#基础知识点 winform底层原理的讲解(发布订阅)实现控件

触发的事件函数

public static void Publisher()
        {
            Phone phone = new Phone()
            {
                Id = 123,
                Name = "华为P9",
                Price = 2499
            };
            // 执行订阅
            Subscriber()//价格变动会触发订阅者里的函数
            phone.Price = 500;
        }

发布者

/// <summary>
        /// 事件的发布者,发布事件并且在满足条件的情况下,触发事件
        /// </summary>
        public class Phone
        {
            public int Id { get; set; }

            public string Name { get; set; }


            private int _price;

            public int Price
            {
                get
                {
                    return _price;
                }
                set
                {
                    if (value < _price) //降价了
                    {
                        this.DiscountHandler?.Invoke(this, new XEventArgs()
                        {
                            OldPrice = _price,
                            NewPrice = value
                        });
                    }

                    this._price = value;

                }
            }

            public event EventHandler DiscountHandler;
        }

订阅者

public static void Subscriber()
        {
            //订阅:就是把订户和事件发布者关联起来
            phone.DiscountHandler += new Teacher().Buy;
            phone.DiscountHandler += new Student().Buy;
        }

订阅者类

/// <summary>
/// 订户 关注事件,事件发生之后,自己做出相应的动作
/// 价格变动会触发BUY函数
/// </summary>
        public class Teacher
        {
            public void Buy(object sender, EventArgs e)
            {
                Phone phone = (Phone)sender;
                Console.WriteLine($"this is {phone.Name}");
                XEventArgs xEventArgs = (XEventArgs)e;
                Console.WriteLine($"之前的价格{xEventArgs.OldPrice}");
                Console.WriteLine($"现在的价格{xEventArgs.NewPrice}");
                Console.WriteLine("买下来");

            }
        }

        public class Student
        {
            public void Buy(object sender, EventArgs e)
            {
                Phone phone = (Phone)sender;
                Console.WriteLine($"this is {phone.Name}");
                XEventArgs xEventArgs = (XEventArgs)e;
                Console.WriteLine($"之前的价格{xEventArgs.OldPrice}");
                Console.WriteLine($"现在的价格{xEventArgs.NewPrice}");
                Console.WriteLine("买下来");

            }
        }

事件参数

public class XEventArgs : EventArgs
        {
            public int OldPrice { get; set; }

            public int NewPrice { get; set; }

        }

猜你喜欢

转载自blog.csdn.net/aa2528877987/article/details/107929934