简体   繁体   中英

How does PropertyChangedEventHandler being created and freed in C#

I have the following code which has a 'PropertyChangedEventHandler'. I see it has a property PropertyChangedEventHandler, but I don't see anywhere it calls 'new PropertyChangedEventHandler'? And do I need to 'null' the reference when I don't need it?

public abstract class MyClass: INotifyPropertyChanged
{
    public event PropertyChangedEventHandler eventHandler;     
}

When you declare an event, the compiler automatically creates a backing field of the target delegate type and two wrapper methods, called "add" and "remove". When you subscribe to the event, the "add" method is internally called and it creates an instance of the underlying delegate(PropertyChangedEventHandler in this case) if not already created.

When you unsubscribe from the event, "remove" method is internally called. If there are no more subscribers, the underlying delegate field is automatically set to null in the "remove" method. So you don't need to set it to null explicitly.

And this is the reason you need to check for null reference before raising the event, because, if there are no subscribers, the underlying field will be null.

This is declared as an event . By default, an event is automatically created as a multicast delegate that can have delegates added to and removed from.

So no, you don't need to do anything. The framework will initialize it and free it as appropriate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM