且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-06-09 01:44:57

我已经在 一篇文章,但这里是摘要,假设您对 代表 自己:

I've written this up in a fair amount of detail in an article, but here's the summary, assuming you're reasonably happy with delegates themselves:

  • 事件只是添加"方法和删除"方法,就像属性实际上只是获取"方法和设置"方法一样.(事实上​​,CLI 也允许使用raise/fire"方法,但 C# 从不生成此方法.)元数据通过对方法的引用来描述事件.
  • 当您声明一个类字段事件(就像您的 ElementAddedEvent)编译器生成方法和一个私有字段(与委托的类型相同).在类中,当您引用 ElementAddedEvent 时,您指的是该字段.在课堂之外,您指的是该领域.
  • 当任何人(使用 += 运算符)订阅调用 add 方法的事件时.当他们取消订阅(使用 -= 运算符)调用删除时.
  • 对于类似字段的事件,有一些同步,否则添加/删除只需调用 Delegate.合并/删除以更改自动生成字段的值.这两个操作都分配给支持字段 - 请记住,委托是不可变的.换句话说,自动生成的代码很像这样:

  • An event is just an "add" method and a "remove" method, in the same way that a property is really just a "get" method and a "set" method. (In fact, the CLI allows a "raise/fire" method as well, but C# never generates this.) Metadata describes the event with references to the methods.
  • When you declare a field-like event (like your ElementAddedEvent) the compiler generates the methods and a private field (of the same type as the delegate). Within the class, when you refer to ElementAddedEvent you're referring to the field. Outside the class, you're referring to the field.
  • When anyone subscribes to an event (with the += operator) that calls the add method. When they unsubscribe (with the -= operator) that calls the remove.
  • For field-like events, there's some synchronization but otherwise the add/remove just call Delegate.Combine/Remove to change the value of the auto-generated field. Both of these operations assign to the backing field - remember that delegates are immutable. In other words, the autogenerated code is very much like this:

// 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<EventArgs> __ElementAddedEvent;

// Actual event
public EventHandler<EventArgs> 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 的行为.

  • The initial value of the generated field in your case is null - and it will always become null again if all subscribers are removed, as that is the behaviour of Delegate.Remove.

    如果你想要一个no-op"处理程序来订阅你的事件,以避免无效性检查,你可以这样做:

    If you want a "no-op" handler to subscribe to your event, so as to avoid the nullity check, you can do:

    public EventHandler<EventArgs> ElementAddedEvent = delegate {};
    

    delegate {} 只是一个匿名方法,它不关心它的参数并且什么都不做.

    The delegate {} is just an anonymous method which doesn't care about its parameters and does nothing.

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

    If there's anything that's still unclear, please ask and I'll try to help!