当前位置:网站首页>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
所以可以直接使用局部函数
边栏推荐
- FRED应用:毛细管电泳系统
- 7 天能找到 Go 工作吗?学学 Go 数组和指针试试
- 数据库恢复
- 广告电商系统开发功能只订单处理
- xampp安装包含的组件有(php,perl,apche,mysql)
- RS|哨兵二号(.SAFE格式)转tif格式
- Basic Introduction for PLSQL
- [The Art of Hardware Architecture] Study Notes (1) The World of Metastability
- Zheng Qing freshmen school competition and middle-aged engineering selection competition
- CF1527D MEX Tree (mex & tree & inclusive)
猜你喜欢

1403. Minimum Subsequence in Non-Increasing Order

Sum of four squares, laser bombs

郑轻新生校赛和中工选拔赛题解

Hangzhou Electric School Competition (Counter Attack Index)

JCMsuite Application: Oblique Plane Wave Propagation Transmission Through Aperture

leetcode: 253. How many meeting rooms are required at least

世间几乎所有已知蛋白质结构,都被DeepMind开源了

CCF GLCC正式开营|九州云开源专家携丰厚奖金,助力高校开源推广

Problem solving-->Online OJ (18)

化繁为简,聊一聊复制状态机系统架构抽象
随机推荐
四平方和,激光炸弹
如何确定异步 I/O 瓶颈
[Beiya data recovery] IBM System Storage storage lvm information lost data recovery solution
centos7安装mysql急速版
leetcode:259. 较小的三数之和
并发程序的隐藏杀手——假共享(False Sharing)
idea removes spark logs
How to write SQL statements: the usage of Update, Case, and Select together
砺夏行动|九州云章津楠:开源不是少数人的运动,大众化才是源泉
Centos7 install mysql version rapidly
leetcode:212. 单词搜索 II
leetcode: 253. How many meeting rooms are required at least
Go 语言快速入门指南: 变量和常量
FRED应用:毛细管电泳系统
爬虫——动作链、xpath、打码平台使用
第十六章 源代码文件 REST API 教程(一)
Find My Technology | Prevent your pet from getting lost, Apple Find My technology can help you
基于 Next.js实现在线Excel
《分布式云最佳实践》分论坛,8月11日深圳见
AOSP内置APP特许权限白名单