呼吁A&QUOT扩展方法;零"参考邪恶的(即没有用户的事件)? [英] Is calling an extension method on a "null" reference (i.e. event with no subscribers) evil?

查看:140
本文介绍了呼吁A&QUOT扩展方法;零"参考邪恶的(即没有用户的事件)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

邪恶或不邪恶?

public static void Raise(this EventHandler handler, object sender, EventArgs args)
{
   if (handler != null)
   {
      handler(sender, args);
   }
}

// Usage:
MyButtonClicked.Raise(this, EventArgs.Empty);

// This works too! Evil?
EventHandler handler = null;
handler.Raise(this, EVentArgs.Empty);

请注意,由于扩展方法的性质,MyButtonClicked.Raise不会抛出一个NullReferenceException如果MyButtonClicked是空值。 (例如有没有听众MyButtonClicked事件)。

Note that due to the nature of extension methods, MyButtonClicked.Raise will not throw a NullReferenceException if MyButtonClicked is null. (E.g. there are no listeners to MyButtonClicked event).

恶不?

推荐答案

不恶。我希望事件默认的工作这条路。有人可以解释为什么没有订户的事件是空?

Not evil. I wish events worked this way by default. Can someone explain why an event with no subscribers is null?

这篇关于呼吁A&QUOT扩展方法;零"参考邪恶的(即没有用户的事件)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆