我已经在文章中详细介绍了这一点,但是这里是总结,假设您对委托人自己很满意:
对于类似字段的事件,需要进行一些同步,否则添加/删除仅调用Delegate。合并 / 删除以更改自动生成的字段的值。这两个操作都分配给后备字段-请记住,委托是不可变的。换句话说,自动生成的代码非常像这样:
// backing field
// The underscores just make it simpler to see what’s going on here. // In the rest of your source code for this class, if you refer to // ElementAddedEvent, you’re really referring to this field. private EventHandler
// Actual event public EventHandler
在您的情况下,所生成字段的初始值为null
-,并且null
如果所有订阅者都被删除,它将始终再次变为初始值,这就是Delegate.Remove的行为。
如果您希望“无操作”处理程序订阅您的事件,以避免无效检查,则可以执行以下操作:
public EventHandler<EventArgs> ElementAddedEvent = delegate {};
的delegate {}
只是它不关心它的参数,所以没有任何一个匿名方法。
如果还有什么不清楚的地方,请询问,我将尽力帮助!