当前位置:网站首页>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
所以可以直接使用局部函数
边栏推荐
猜你喜欢
技术分享| 融合调度系统中的电子围栏功能说明
ASA归因:如何评估关键词的投放价值
I/O stream summary
在腾讯,我的试用期总结!
leetcode:251. 展开二维向量
Almost all known protein structures in the world are open sourced by DeepMind
Compound Refractive Lenses for X-ray Focusing
爬虫——selenium基本使用、无界面浏览器、selenium的其他用法、selenium的cookie、爬虫案例
leetcode:254. 因子的组合
Google plug-in. Download contents file is automatically deleted after solution
随机推荐
NPDP|作为产品经理,如何快速提升自身业务素养?
华为云 & 达达,帮有情人“一键送达”
B. Construct a simple sequence (greedy)
leetcode:259. 较小的三数之和
CCF GLCC officially opened | Kyushu Cloud open source experts bring generous bonuses to help universities promote open source
token 过期后,如何自动续期?
【Today in History】August 4: First female Turing Award winner; NVIDIA acquires MediaQ; first Cybersecurity Challenge completed
【历史上的今天】8 月 4 日:第一位图灵奖女性得主;NVIDIA 收购 MediaQ;首届网络安全挑战大赛完成
并发程序的隐藏杀手——假共享(False Sharing)
CloudCompare&PCL 点云按网格划分(点云分幅)
砺夏行动|九州云章津楠:开源不是少数人的运动,大众化才是源泉
Sum of four squares, laser bombs
vim common operation commands
特殊品种的二次开户验资金额
X射线掠入射聚焦反射镜
Centos7 install mysql version rapidly
Leetcode: 215 disorderly to find the first big k element in the array
ASA归因:如何评估关键词的投放价值
leetcode:253. 至少需要多少间会议室
leetcode: 254. Combinations of factors