Raising Inherited Events in C#
When working with inheritance in C#, it's important to understand how to properly access and raise events that are declared in a base class.
Suppose you have a base class with the following events defined:
public event EventHandler Loading; public event EventHandler Finished;
In a class that inherits from this base class, you may encounter an error when attempting to raise these events directly, such as:
this.Loading(this, new EventHandler()); // Error: The event 'BaseClass.Loading' can only appear on the left hand side of += or -=
This error occurs because events are not accessible like ordinary inherited members. To raise events from an inherited class, the following approach should be used:
protected virtual void OnLoading(EventArgs e) { EventHandler handler = Loading; if(handler != null) { handler(this, e); } } protected virtual void OnFinished(EventArgs e) { EventHandler handler = Finished; if(handler != null) { handler(this, e); } }
public class InheritedClass : BaseClass { public void DoSomeStuff() { ... OnLoading(EventArgs.Empty); ... OnFinished(EventArgs.Empty); } }
By using protected methods to raise events in a base class, you can ensure that event handlers are properly invoked from derived classes while maintaining the encapsulation of the event-raising mechanism.
The above is the detailed content of How Can I Properly Raise Inherited Events in C#?. For more information, please follow other related articles on the PHP Chinese website!