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

How to Properly Raise Inherited Events in C#?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-26 12:07:10895browse

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 protected methods can be modified to check whether the event handler needs to be invoked (e.g., by checking handler.GetInvocationList().Length > 0).
  • This approach ensures that events can be raised and handled in a consistent manner throughout the inheritance hierarchy.

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!

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