C# 委托、事件、Func、Action
委托:
在 .NET 中委托提供后期绑定机制。 后期绑定意味着调用方在你所创建的算法中至少提供一个方法来实现算法的一部分,它允许将方法作为参数传递给其他方法
可以把委托想象成一个合同,规定了方法的签名(比如方法的参数类型和返回值)。这个合同允许你将一个符合这个签名的方法绑定到委托上。当委托被调用时,它就会执行绑定的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | string a, b, x; static int CWStr( int s) { return s; } static int Add( int a) { return a + 10; } static int DoSomeSthing(MyDelegate myD) { myD += Add; return myD(100); } MyDelegate myD = null ; myD += Add; a = myD(10) + "" ; myD = CWStr; b = $ "This Is Console Word:{myD(20)}" ; x = DoSomeSthing(myD) + "" ; Console.WriteLine($ "{a},\r\n{b},\r\n{x}" ); Console.ReadKey(); public delegate int MyDelegate( int a); |
在委托delegate出现了很久以后,微软的.NET设计者们终于领悟到,其实所有的委托定义都可以归纳并简化成只用Func与Action这两个语法糖来表示。
其中,Func代表有返回值的委托,Action代表无返回值的委托。有了它们两,我们以后就不再需要用关键字delegate来定义委托了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | string a, b, x; static int CWStr( int s) { return s; } static int Add( int a) { return a + 10; } static int DoSomeSthing(Func< int , int > myD) { myD = Add; return myD(100); } Func< int , int > myD = null ; myD += Add; a = myD(10) + "" ; myD = CWStr; b = $ "This Is Console Word:{myD(20)}" ; x = DoSomeSthing(myD) + "" ; Console.WriteLine($ "{a},\r\n{b},\r\n{x}" ); Console.ReadKey(); |
事件
事件是一种特殊的委托,且只能用+=或-=
事件是对象用于(向系统中的所有相关组件)广播已发生事情的一种方式。 任何其他组件都可以订阅事件,并在事件引发时得到通知,它允许一个对象将状态的变化通知其他对象,而不需要知道这些对象的细节
可以把它理解为一个通知系统:一个对象(事件的“发布者”)发布事件,其他对象(事件的“订阅者”)可以订阅这个事件,收到通知后做出反应。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | Cat cat = new Cat(); new People(cat); new Mouse(cat); cat.DoSomting(); public delegate void ActionHandler(); class Cat { public event ActionHandler Action; public void DoSomting() { Console.WriteLine( "猫叫了一声" ); Action?.Invoke(); } } class People { public People(Cat cat) { cat.Action += () => { Console.WriteLine( "人醒了" ); }; } } class Mouse { public Mouse(Cat cat) { cat.Action += () => { Console.WriteLine( "老鼠跑了" ); }; } } |
分类:
.Net 6相关
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)