呼吁A"扩展方法;零"参考邪恶的(即没有用户的事件)?

问题描述:

邪恶或不邪恶?

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?