C#中的委托和事件
作者:農碼一生 时间:2021-09-14 01:01:55
一、定义委托
delegate void StudentDelegate();//【1】定义一个委托
二、定义一个调用和定义事件的类
/// <summary>
///定义事件和调用 事件一定要放在一个类里面
/// </summary>
class InvokeDefine //【2】定义一个调用和定义事件的类
{
public event StudentDelegate StudentEvent;
public void Invoke()
{
StudentEvent?.Invoke();//?.Null检查运算符
}
}
三、订阅者
class EventFunction //【3】订阅者
{
public void Student1()
{
Console.WriteLine("我是订阅者1");
}
public void Student2()
{
Console.WriteLine("我是定订阅者2");
}
}
四、订阅事件
static void Main(string[] args)
{
EventFunction eventFunction = new EventFunction();
InvokeDefine invokeDefine = new InvokeDefine();
invokeDefine.StudentEvent += eventFunction.Student1;//【4】订阅事件
invokeDefine.StudentEvent += eventFunction.Student2;
invokeDefine.Invoke();
Console.ReadKey();
}
五、总结
第一点:在定义事件类的外部,他是不能使用=号来操作,只能用+=。
第二点:在定义事件类的外部不能调用 事件。
第三点:事件就是在委托的前面增加一个event关键字。
来源:https://www.cnblogs.com/wml-it/p/16044564.html
标签:C#,委托,事件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
C#多态的三种实现方式(小结)
2022-12-29 18:10:57
解决WPF附加属性的Set函数不调用的问题
2022-09-27 09:52:38
VS2019配置opencv详细图文教程和测试代码的实现
2023-07-17 13:49:31
![](https://img.aspxhome.com/file/2023/8/100298_0s.png)
java开发RocketMQ消息中间件原理基础详解
2023-10-01 21:04:49
java教程之java注解annotation使用方法
2023-11-13 20:18:57
SpringBoot全局异常处理与定制404页面的方法
2021-08-07 18:54:56
![](https://img.aspxhome.com/file/2023/9/64759_0s.png)
SpringBoot如何读取xml配置bean(@ImportResource)
2021-08-03 22:33:44
![](https://img.aspxhome.com/file/2023/8/85888_0s.jpg)
学生信息管理系统java版
2023-06-16 15:48:10
Java JDK动态代理(AOP)用法及实现原理详解
2021-11-14 16:45:21
![](https://img.aspxhome.com/file/2023/2/69292_0s.png)
安卓系统中实现摇一摇画面振动效果的方法
2023-12-05 02:53:53
![](https://img.aspxhome.com/file/2023/1/77401_0s.png)
Java中的复合数据类型
2022-10-05 08:08:08
![](https://img.aspxhome.com/file/2023/3/69273_0s.png)
Java List集合排序实现方法解析
2023-01-06 05:40:14
简单介绍Android开发中的Activity控件的基本概念
2022-02-23 23:46:21
![](https://img.aspxhome.com/file/2023/9/90129_0s.png)
C# Winform 实现控件自适应父容器大小的示例代码
2021-06-15 20:00:52
Java 8 lambda表达式引入详解及实例
2022-10-25 22:41:37
android 多点触摸图片缩放的具体实现方法
2023-03-14 05:49:31
Java基础-Java的体系结构
2022-05-18 00:19:05
![](https://img.aspxhome.com/file/2023/1/63501_0s.png)
java修改JFrame默认字体方式
2022-11-16 14:02:50
用java在web环境下上传和下载文件的技巧
2021-06-09 18:17:17
java实现简单的验证码功能
2023-08-06 09:21:44