Home > Backend Development > C++ > How to Correctly Raise Inherited Events in C# Derived Classes?

How to Correctly Raise Inherited Events in C# Derived Classes?

Linda Hamilton
Release: 2024-12-25 16:03:10
Original
361 people have browsed it

How to Correctly Raise Inherited Events in C# Derived Classes?

Raising Inherited Events in C

In object-oriented programming, it is common for classes to inherit events from their base classes. However, raising those inherited events can lead to confusion. This question addresses the error faced when attempting to raise an inherited event in a derived class, and provides a solution for it.

Problem

In a base class defined as follows:

public class BaseClass
{
    public event EventHandler Loading;
    public event EventHandler Finished;
}
Copy after login

A derived class tries to raise the inherited event:

public class DerivedClass : BaseClass
{
    // Error: 'BaseClass.Loading' can only appear on the left hand side of += or -=
    this.Loading(this, new EventHandler());
}
Copy after login

This error indicates that the event cannot be accessed directly using the "this" keyword.

Solution

To raise an inherited event, you need to define protected methods in the base class to handle the event invocation. These methods allow for the event to be raised even when the derived class overrides the event.

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);
    }

    // Invoking the events from the derived class
    public class DerivedClass : BaseClass
    {
        public void RaiseLoadingEvent()
        {
            OnLoading(EventArgs.Empty);
        }

        public void RaiseFinishedEvent()
        {
            OnFinished(EventArgs.Empty);
        }
    }
}
Copy after login

By calling OnLoading or OnFinished in the derived class, the handlers subscribed to the events in the base class will be invoked, ensuring proper event handling in the derived classes.

The above is the detailed content of How to Correctly Raise Inherited Events in C# Derived Classes?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template