Home >Backend Development >C++ >How to Properly Raise Inherited Events in C#?
How to Raise Inherited Events in C#
In C#, events can be declared in base classes and accessed by derived classes. However, raising events in inherited classes requires specific handling.
Problem:
When attempting to raise an event inherited from a base class, you may encounter an error stating that the event can only appear on the left-hand side of the = or -= operators.
Solution:
To raise inherited events, you must create protected methods in the base class that can be used to invoke the events. These methods should follow the naming convention "OnEventName".
For example, consider the following base class:
public class BaseClass { public event EventHandler Loading; public event EventHandler Finished; }
Protected Event Raising Methods:
In the base class, create protected methods like the following:
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); } }
Raising Events in Derived Class:
In the derived class, call the protected methods to raise the events:
public class DerivedClass : BaseClass { public void DoSomething() { ... OnLoading(EventArgs.Empty); ... OnFinished(EventArgs.Empty); } }
Note:
The above is the detailed content of How to Properly Raise Inherited Events in C#?. For more information, please follow other related articles on the PHP Chinese website!