如何在调用函数时自动调用事件?

the*_*row 5 .net c# events .net-3.5

我有这样的代码:

public class Foo
{
  public SomeHandler OnBar;

  public virtual void Bar()
  {
  }
}
Run Code Online (Sandbox Code Playgroud)

Foo是一个基类,因此其他类可能会继承它.
我希望OnBarBar()调用时始终触发该事件,即使它未在Bar中明确调用.
怎么做到呢?

Qua*_*ter 9

一种常见的模式是使用非虚拟方法来执行您想要的调用虚方法的方法.子类可以覆盖内部方法以更改功能,但公共方法可以是非虚拟的,始终首先引发事件.

public class Foo
{
    public SomeHandler OnBar;

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

    protected virtual void BarImpl()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)