How to automatically trigger an event when a function is called?

I have a code like this:

public class Foo
{
  public SomeHandler OnBar;

  public virtual void Bar()
  {
  }
}

Foo is a base class, and therefore other classes can inherit it.
I would like the event to OnBaralways fire when it is called Bar(), even if it is not called explicitly inside the panel.
How can I do that?

+5
source share
4 answers

A common pattern is to have a non-virtual method that will do what you want to call the virtual method. Subclasses may override the internal method to change functionality, but the public method may not be virtual, always raising the event first.

public class Foo
{
    public SomeHandler OnBar;

    public void Bar()
    {
        if (OnBar != null)
        {
            OnBar(this, EventArgs.Empty);
        }
        BarImpl();
    }

    protected virtual void BarImpl()
    {
    }
}
+9

: . , Microsoft .

, "- " .NET. Google, - .

:. - Bar(), , . .

+2

, , .
.

, - .

public class Foo
{
  public SomeHandler OnBar;

  public void Bar()
  {
     OnBar();  (check for nulls)
     ProtectedBar();
  }

  protected virtual ProtectedBar()
  {
  }
}
+1

, - Aspect Oriented Programming.

This will help you with “confusing code” (i.e., calling an event in a method that should not have this responsibility) and “scattered code” (i.e., calling the same event in multiple methods, duplicating your code).

You should take a look at postsharp , it has a free community version.

0
source

All Articles