问题描述
为事件定义一个空委托体是一个很好的做法,这样就不用担心引发没有事件处理程序的事件? (不需要检查事件是否为空)
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 :)
这篇关于为事件定义一个空委托体是一个很好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!