Raising Events Inherited from a Base Class in C#
In C#, it is common practice to inherit events from a base class to facilitate event handling in derived classes. However, raising such inherited events requires a specific approach to avoid compiler errors.
Consider a scenario where a base class defines the following events:
public class BaseClass { public event EventHandler Loading; public event EventHandler Finished; }
In a derived class, attempting to raise the Loading event using:
this.Loading(this, new EventHandler());
results in the error:
The event 'BaseClass.Loading' can only appear on the left hand side of += or -= (BaseClass')
This error occurs because events, unlike other class members, cannot be invoked directly by the derived class. Instead, inherited events must be raised by invoking specific methods defined in the base class. To achieve this, the following steps are necessary:
public class BaseClass { public event EventHandler Loading; public event EventHandler Finished; 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 DerivedClass : BaseClass { public void DoSomething() { // Raise Loading event OnLoading(EventArgs.Empty); // Raise Finished event OnFinished(EventArgs.Empty); } }
By following this approach, inherited events can be safely and efficiently raised in derived classes in C#.
The above is the detailed content of How Can I Properly Raise Inherited Events in C# Derived Classes?. For more information, please follow other related articles on the PHP Chinese website!