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

How Can I Properly Raise Inherited Events in C#?

DDD
Release: 2024-12-25 20:02:15
Original
777 people have browsed it

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;
Copy after login

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 -= 
Copy after login

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);
    }
}
Copy after login
  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);
    }
}
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template