Is it a good practice to define an empty delegate body for a event?(为事件定义一个空的委托主体是一个好习惯吗?)
问题描述
可能重复:
添加有缺点吗事件声明上的匿名空委托?
为事件定义一个空的委托主体,这样您就不必担心引发没有事件处理程序的事件,这是一种好习惯吗?(无需检查事件是否为空).
Is it a good practice to define an empty delegate body for a event so that you do not need to worry raise a event which have no event handler? ( no need to check whether event is null).
如下代码:
public event EventHandler<LoadEventArgs> LoadedData = delegate { };
推荐答案
我确实发现它很有用,是的.会有非常小的性能成本 - 但不必执行无效测试的可读性优势使其值得 IMO.
I've certainly found it useful, yes. There will be a tiny, tiny performance cost - but the benefit in readability for not having to perform the nullity test makes it worth it IMO.
值得指出的是,这是少数使用匿名方法而不是 lambda 表达式更好的情况之一 - 否则您必须命名将要忽略的参数,如下所示:
It's worth pointing out that this is one of the few times when it's good to use an anonymous method rather than a lambda expression - otherwise you have to name the parameters that you're going to ignore, like this:
public event EventHandler<LoadEventArgs> LoadedData = (sender, args) => {};
我不喜欢为我不打算使用的东西命名:)
I don't like having to name things I'm not intending to use :)
这篇关于为事件定义一个空的委托主体是一个好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为事件定义一个空的委托主体是一个好习惯吗?


基础教程推荐
- JSON.NET 中基于属性的类型解析 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01