为事件定义一个空的委托主体是一个好习惯吗?

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 :)

这篇关于为事件定义一个空的委托主体是一个好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)