本文介绍了为事件定义一个空的委托主体是一个好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
添加有缺点吗事件声明上的匿名空委托?

为事件定义一个空的委托主体,这样您就不必担心引发没有事件处理程序的事件,这是一种好习惯吗?(无需检查事件是否为空).

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

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

08-04 18:37