您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

C#事件如何在后台工作?

C#事件如何在后台工作?

我已经在文章中详细介绍了这一点,但是这里是总结,假设您对委托人自己很满意:

对于类似字段的事件,需要进行一些同步,否则添加/删除调用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 __ElementAddedEvent;

// Actual event public EventHandler ElementAddedEvent { add { lock(this) { // Equivalent to __ElementAddedEvent += value; __ElementAddedEvent = Delegate.Combine(__ElementAddedEvent, value); } } remove { lock(this) { // Equivalent to __ElementAddedEvent -= value; __ElementAddedEvent = Delegate.Remove(__ElementAddedEvent, value); } } }

在您的情况下,所生成字段的初始值为null-,并且null如果所有订阅者都被删除,它将始终再次变为初始值,这就是Delegate.Remove的行为。

如果您希望“无操作”处理程序订阅您的事件,以避免无效检查,则可以执行以下操作:

public EventHandler<EventArgs> ElementAddedEvent = delegate {};

delegate {}只是它不关心它的参数,所以没有任何一个匿名方法

如果还有什么不清楚的地方,请询问,我将尽力帮助!

c# 2022/1/1 18:15:56 有449人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶