当前位置:网站首页>C# 局部函数与事件
C# 局部函数与事件
2022-08-04 14:48:00 【林德熙】
本文告诉大家使用局部函数可能遇到的坑。
在以前,如果有一个事件public event EventHandler Foo
和一个函数private void Program_Foo(object sender, EventArgs e)
那么使用函数监听事件是很简单的,当然从事件取消函数也是很简单。请看下面代码
for (int i = 0; i < 100; i++)
{
Foo -= Program_Foo;
Foo += Program_Foo;
}
Console.WriteLine(Foo.GetInvocationList().Length);
结果输出 1
因为GetInvocationList
是获得事件有多少监听,从上面代码看到,只有一个监听。
如果把函数修改为局部,请看代码
for (int i = 0; i < 100; i++)
{
Foo -= Program_Foo;
Foo += Program_Foo;
}
Console.WriteLine(Foo.GetInvocationList().Length);
void Program_Foo(object sender, EventArgs e)
{
}
现在他会输出什么?
看起来没有问题,但是如果再做出一些修改,请看下面代码
for (int i = 0; i < 100; i++)
{
F();
}
Console.WriteLine(Foo.GetInvocationList().Length);
private static void F()
{
Foo -= Program_Foo;
Foo += Program_Foo;
void Program_Foo(object sender, EventArgs e)
{
}
}
现在输出是什么?
还是 1
所以可以直接使用局部函数
边栏推荐
- G.登山小分队(暴力&dfs)
- [LeetCode] 38. Appearance sequence
- 杭电校赛(逆袭指数)
- 7 天能找到 Go 工作吗?学学 Go 数组和指针试试
- 【历史上的今天】8 月 4 日:第一位图灵奖女性得主;NVIDIA 收购 MediaQ;首届网络安全挑战大赛完成
- X-ray grazing incidence focusing mirror
- leetcode:250. 统计同值子树
- Lixia Action | Kyushu Yunzhang Jinnan: Open source is not a movement for a few people, popularization is the source
- 化繁为简,聊一聊复制状态机系统架构抽象
- leetcode:215无序数组中找第k大的元素
猜你喜欢
leetcode: 259. Smaller sum of three numbers
leetcode:215无序数组中找第k大的元素
实际工作中的高级技术(训练加速、推理加速、深度学习自适应、对抗神经网络)
并发程序的隐藏杀手——假共享(False Sharing)
【HMS core】【Media】【视频编辑服务】 在线素材无法展示,一直Loading状态或是网络异常
This week to discuss the user experience: Daedalus Nemo to join Ambire, explore the encryption of the ocean
Cisco-小型网络拓扑(DNS、DHCP、网站服务器、无线路由器)
数据库恢复
广告电商系统开发功能只订单处理
leetcode: 250. Count subtrees of equal value
随机推荐
leetcode: 251. Expanding 2D Vectors
AOSP built-in APP franchise rights white list
Notes for xpath getting node with namespace
期货开户之前要谈好最低手续费和交返
vim common operation commands
leetcode: 212. Word Search II
Theory 1: Deep Learning - Detailed Explanation of the LetNet Model
企业级优化
X-ray grazing incidence focusing mirror
基于 Next.js实现在线Excel
1403. 非递增顺序的最小子序列
B.构造一个简单的数列(贪心)
CF1527D MEX Tree(mex&树&容斥)
微软表示将向内部网络安全专家共享数据 为企业提供更安全保护
leetcode: 250. Count subtrees of equal value
用于X射线聚焦的复合折射透镜
leetcode: 241. Designing precedence for arithmetic expressions
基于 Next.js实现在线Excel
指数族分布与最大熵
Win10无法访问移动硬盘怎么解决