当前位置:网站首页>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
所以可以直接使用局部函数
边栏推荐
- leetcode:212. 单词搜索 II
- Chinese valentine's day, of course, to learn SQL optimization better leave work early to find objects
- How to write SQL statements: the usage of Update, Case, and Select together
- 【北亚数据恢复】IBM System Storage存储lvm信息丢失数据恢复方案
- 广告电商系统开发功能只订单处理
- How to install postgresql and configure remote access in ubuntu environment
- This week to discuss the user experience: Daedalus Nemo to join Ambire, explore the encryption of the ocean
- leetcode: 241. Designing precedence for arithmetic expressions
- 【硬件架构的艺术】学习笔记(1)亚稳态的世界
- leetcode:250. 统计同值子树
猜你喜欢
uni-app 从零开始-生命周期(二)
[Beiya data recovery] IBM System Storage storage lvm information lost data recovery solution
快解析结合友加畅捷U+
NPDP|作为产品经理,如何快速提升自身业务素养?
token 过期后,如何自动续期?
用于X射线聚焦的复合折射透镜
Lixia Action | Kyushu Yunzhang Jinnan: Open source is not a movement for a few people, popularization is the source
idea removes spark logs
输入输出流总结
CloudCompare&PCL 点云按网格划分(点云分幅)
随机推荐
FRED Application: Capillary Electrophoresis System
Zheng Qing freshmen school competition and middle-aged engineering selection competition
word2003按空格键为什么会出现小数点
华为云 & 达达,帮有情人“一键送达”
vim 常用操作命令
Android Sqlite3 basic commands
G.登山小分队(暴力&dfs)
杭电校赛(ACM组队安排)
Win10无法访问移动硬盘怎么解决
指数族分布与最大熵
leetcode: 253. How many meeting rooms are required at least
并发程序的隐藏杀手——假共享(False Sharing)
leetcode:259. 较小的三数之和
leetcode: 241. Designing precedence for arithmetic expressions
【 HMS core 】 【 Media 】 online video editing service 】 【 material can't show, or network anomalies have been Loading state
using关键字学习
AOSP内置APP特许权限白名单
AOSP built-in APP franchise rights white list
leetcode: 250. Count subtrees of equal value
本周讨论用户体验:Daedalus 的 Nemo 加入 Ambire,探索加密海洋