委托事件&事件的标准写法

using Delegate.Event;
using System;

namespace Delegate
{
    class Program
    {
        static void Main(string[] args)
        {
            #region  委托
            //委托在IL是一个类,继承自System.MulticastDelegate特殊类,不能被继承
            //委托三步骤 1、声明;2、实例化;3调用  Invoke/Invoke也可以省略
            //委托多播   有返回值的多播只会认最后一个   多播委托不能异步
            //MyDelegate myDelegate = new MyDelegate();
            myDelegate.show();
            myDelegate.delegate1.Invoke();
            //Action action1 = () => Console.WriteLine("");

            //Action<string> action = (name) => Console.WriteLine(name);
            //action += (name) => Console.WriteLine($"This is second action:{name}");
            //myDelegate.show2("wang", action);
            #endregion

            #region 事件Event
            //新语法 加?判断变量不为空执行后面的方法,如果为空不执行后面的方法
            string aa = null;
            var bb = "";
            bb = aa?.ToLower();

            //常规写法  
            //依赖太重,任何类型的变化都得修改Miao方法
            //职责耦合  猫不仅自己喵,还得实例化各种对象执行他们的方法,甚至还要控制顺序
            Cat cat = new Cat();
            cat.Miao();

            //委托写法
            //委托是一种类型,事件是委托的实例
            cat.action += new Dog().Wang;
            cat.action += new Mouse().Run;
            //cat.action = null;
            cat.MiaoAction();

            //事件写法
            //事件Event  是委托的实例,加event关键字
            //限制权限  只允许在事件声明类中赋值和invoke,不允许在外面包括子类
            //为啥要用事件?把固定动作和可变动作分开,完成固定动作,可变动作分出去由外部控制,支持扩展
            cat.actionhandler += new Dog().Wang;
            cat.actionhandler += new Mouse().Run;
            //cat.actionhandler = null; //不允许
            cat.MiaoEvent();

            //观察者模式
            cat.ObserverAdd(new Dog());
            cat.ObserverAdd(new Mouse());
            cat.MiaoObserver();

            //标准事件 事件发布者,订户,订阅将发布者和订户关联,事件参数
            new EventStandard().Subscribe();
            #endregion


        }
    }
}
using System;
using System.Collections.Generic;
using System.Text;

namespace Delegate
{
    public delegate int IntResultWithPara(ref string refvalue, out string outvalue);

    public class MyDelegate
    {
        //委托在IL是一个类,继承自System.MulticastDelegate特殊类,不能被继承
        //委托三步骤 1、声明;2、实例化;3调用  Invoke/Invoke也可以省略
        public delegate void NoResultNoPara();
        public delegate int IntResultNoPara();
        public delegate string StrResultWithPara();
        public delegate int IntResultWithPara(ref string refvalue, out string outvalue);

        protected void MyMethod()
        {
            Console.WriteLine("NoResultNoPara");
        }

        //private sealed void MyMethod1()
        //{
        //    Console.WriteLine("NoResultNoPara");
        //}

        private int MyMethod1(ref string rv, out string ov)
        {
            Console.WriteLine("IntResultWithPara");
            ov = "ov";
            return 1;
        }
        public void show()
        {
            NoResultNoPara delegate0 = new NoResultNoPara(this.MyMethod);//实例化委托
            delegate0.Invoke();//调用
            delegate0();//省略Invoke
            IntResultWithPara delegate3 = MyMethod1;
            string rv = "";
            delegate3.Invoke(ref rv, out string ov);
            Console.WriteLine(ov);
        }
        public NoResultNoPara delegate1 = new NoResultNoPara(() => Console.WriteLine("NoResultNoPara"));
        public NoResultNoPara delegate2 = () => Console.WriteLine("NoResultNoPara");
        public void show2(string name, Action<string> action)
        {
            action.Invoke(name);
        }

    }

    public class MyDelegate1 : MyDelegate
    {

    }
}

事件

using System;
using System.Collections.Generic;
using System.Text;

namespace Delegate.Event
{
    public class Cat
    {
        //常规写法  
        //依赖太重,任何类型的变化都得修改Miao方法
        //职责耦合  猫不仅自己喵,还得实例化各种对象执行他们的方法,甚至还要控制顺序
        public void Miao()
        {
            Console.WriteLine($"{this.GetType().Name} : miao~");
            new Dog().Wang();
            new Mouse().Run();
        }

        //委托写法
        //猫只用关心自己的逻辑
        public Action action;
        public void MiaoAction()
        {
            Console.WriteLine($"{this.GetType().Name} : miaoDelegate~");
            action?.Invoke();
        }

        //事件写法
        //事件Event  是委托的实例,加event关键字
        //限制权限  只允许在事件声明类中赋值和invoke,不允许在外面包括子类
        //为啥要用事件?把固定动作和可变动作分开,完成固定动作,可变动作分出去由外部控制,支持扩展
        public event Action actionhandler;
        public void MiaoEvent()
        {
            Console.WriteLine($"{this.GetType().Name} : miaoEvent~");
            actionhandler?.Invoke();
        }

        //观察者模式
        private List<IObject> _observer = new List<IObject>();
        public void ObserverAdd(IObject @object)
        {
            _observer.Add(@object);
        }
        public void MiaoObserver()
        {
            Console.WriteLine($"{this.GetType().Name} : miaoObserver~");
            foreach (IObject @object in _observer)
            {
                @object.DoAction();
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Text;

namespace Delegate.Event
{
    /// <summary>
    /// 定义接口,狗和老鼠类继承这个接口
    /// </summary>
    public interface IObject
    {
        void DoAction();
    }
}
using System;
using System.Collections.Generic;
using System.Text;

namespace Delegate.Event
{
    public class Dog : IObject
    {
        public void DoAction()
        {
            this.Wang();
        }
        public void Wang()
        {
            Console.WriteLine($"{this.GetType().Name} : wang~");
        }
    }
}

事件标准写法

using System;
using System.Collections.Generic;
using System.Text;

namespace Delegate.Event
{
    public class EventStandard
    {
        //事件参数类
        public class XEventArgs : EventArgs
        {
            public int OldPrice { set; get; }
            public int NewPrice { set; get; }
        }

        //订阅
        public void Subscribe()
        {
            iPhoneX iPhoneX = new iPhoneX()
            {
                Name = "iPhone",
                Price = 6000,
            };
            iPhoneX.DiscountHandler += new Student().Buy;
            iPhoneX.Price = 5000;
        }

        //订户
        public class Student
        {
            public void Buy(object sender, EventArgs e)
            {
                iPhoneX iphoneX = (iPhoneX)sender;
                XEventArgs xEventArgs = (XEventArgs)e;
                Console.WriteLine($"{iphoneX.Name}之前的价格:{xEventArgs.OldPrice},现在的价格:{xEventArgs.NewPrice},买买买!");
            }
        }

        //事件发布者
        public class iPhoneX
        {
            public string Name { set; get; }
            private int _price;
            public int Price
            {
                set
                {
                    if (value < _price)
                    {
                        DiscountHandler?.Invoke(this, new XEventArgs()
                        {
                            OldPrice = _price,
                            NewPrice = value
                        });
                    }
                    _price = value;
                }
                get
                {
                    return this._price;
                }
            }
            public event EventHandler DiscountHandler;
        }
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值