委托的特点
委托的本质是一个什么,委托的本质是一个类,继承自一个特殊的MulticastDelegate 同时这个特殊的类程序员是无法继承的。
委托 可以通过new来实例化 ,要求传递一个和委托的参数返回值相同的方法进去
委托的实力可以指向 跟这个委托的参数和返回值相同的方法
执行委托的实力Invoke方法去执行这个委托所指向或者所传递进去的方法
(需要注意的是方法在传递的时候 不要加()因为方法一但加了括号 就是直接执行了)
委托的作用和意义
委托有一个延迟执行方法的功效(当看到中间件源码时就更能感受到了)
逻辑解耦,重用;
在什么地方可以使用委托
方法业务逻辑耦合严重
多个方法且代码逻辑重复过多
自定义委托和内置委托
自定义
//无参数,无返回值 public delegate void ShowDelegate(); |
//有参数有返回值 public delegate int ShowDelegate(int s) |
内置
Action 无返回值 |
Func 有返回值 |
事件 是委托的封装,为了使委托更安全,因为他只能在类的内部调用
事件的本质是两个方法, addevent 和 removeevent 和一个私有的委托变量这两个方法就是对这个私有委托变量的合并和移除对应的是+=,-=
事件只能从对象的外部增加相应的方法和删除相应的方法,并且不能主动触发和获取其他注册的相应方法信息
委托则没有这些限制
这是事件给委托 增加的限制
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyDelegate { public class EventStandard2 { public static void Show() { AdvancedClass frameworkClass = new AdvancedClass() { Id = 1, Name = "事件丛书,订阅模式", Price = 4299 }; //订阅:就是个订户和事件发布者关联起来 //这里注意类的内部定义事件,在外部注册事件 frameworkClass.PriceIncrease += new StudentInfo().Buy; frameworkClass.PriceIncrease += new Tencent().Extension; ///注册完毕之后在适当时机进行调用 frameworkClass.Price = 6299; } /// <summary> /// 订户: 关注事件,事件触发后,自己做出相应的动作 /// </summary> public class StudentInfo { public void Buy(object sender, EventArgs e) { AdvancedClass frameworkClass = (AdvancedClass)sender; AdvancedClassEventArge eventArge = (AdvancedClassEventArge)e; Console.WriteLine($"this is {frameworkClass.Name}"); Console.WriteLine($"{frameworkClass.Name}之前的价格是{eventArge.OldPrice}"); Console.WriteLine($"{frameworkClass.Name}现在要马上更新的价格是{eventArge.NewPrice}"); Console.WriteLine("果断买了。。。"); Console.WriteLine($"{frameworkClass.Name}现在要马上更新的价格是{eventArge.NewPrice}"); } } /// <summary> /// 订户,关注事件,事件触发之前,做出点动作 /// </summary> public class Tencent { public void Extension(object sender, EventArgs e) { AdvancedClass frameworkClass = (AdvancedClass)sender; AdvancedClassEventArge eventArge = (AdvancedClassEventArge)e; Console.WriteLine($"this is {frameworkClass.Name}"); Console.WriteLine($"{frameworkClass.Name}之前的价格是{eventArge.OldPrice}"); Console.WriteLine($"{frameworkClass.Name}现在要马上更新的价格是{eventArge.NewPrice}"); Console.WriteLine("马上推广一波。。"); } } public class AdvancedClassEventArge : EventArgs { public int OldPrice { get; set; } public int NewPrice { get; set; } } /// <summary> /// 事件的发布者,发布是按并且在满足条件的情况下,触发事件 /// </summary> public class AdvancedClass { public int Id { get; set; } public string Name { get; set; } private int _price = 5299; public int Price { get { return _price; } set { if (value > _price) { ///触发一部分动作 出发 委托要求类型的方法 PriceIncrease.Invoke(this, new AdvancedClassEventArge() { OldPrice = _price, NewPrice = value }); } _price = value; } } //这个eventhandler 是一个委托 事件的提供程序 委托要求的方法参数为 一个 object 和一个 enventarge // object sender 是事件源,也就是上边invok 的this eventtarge 则是需要传递的参数 需要继承自 eventarge类来增加参数然后传递 public event EventHandler PriceIncrease; } } } |