Home >Backend Development >C++ >How Can I Properly Raise Inherited Events in C#?

How Can I Properly Raise Inherited Events in C#?

DDD
DDDOriginal
2024-12-25 20:02:15823browse

How Can I Properly Raise Inherited Events in C#?

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:

  1. In the base class, create protected methods that can be used to raise the events. These methods should be named using the prefix "On" followed by the event name:
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);
    }
}
  1. In classes that inherit from this base class, the OnLoading and OnFinished methods can be called to raise the events:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn