当前位置:网站首页>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
所以可以直接使用局部函数
边栏推荐
- 广告电商系统开发功能只订单处理
- Makefile syntax and usage notes
- Why does the decimal point appear when I press the space bar in word 2003?
- Zheng Qing freshmen school competition and middle-aged engineering selection competition
- 企业级优化
- idea removes spark logs
- leetcode: 241. Designing precedence for arithmetic expressions
- 【硬件架构的艺术】学习笔记(1)亚稳态的世界
- Hangzhou electric the competition team arrangement (ACM)
- 指数族分布与最大熵
猜你喜欢
随机推荐
SQL语句的写法:Update、Case、 Select 一起的用法
F.金玉其外矩阵(构造)
谷歌插件.crx文件下载后被自动删除的解决方法
leetcode: 212. Word Search II
16、学习MySQL 正则表达式
Makefile syntax and usage notes
我爱七夕哈哈哈
JCMsuite Application: Oblique Plane Wave Propagation Transmission Through Aperture
杭电校赛(逆袭指数)
vim common operation commands
企业级优化
xampp安装包含的组件有(php,perl,apche,mysql)
Android Sqlite3 basic commands
数据链路层-------以太网协议
CF1527D MEX Tree(mex&树&容斥)
leetcode: 255 Verify preorder traversal sequence binary search tree
解题-->在线OJ(十八)
Centos7 install mysql version rapidly
word2003按空格键为什么会出现小数点
leetcode: 259. Smaller sum of three numbers









