5

In my abstract class can I listen an abstract method and fire an event whenever that method is called? If yes how?

emregon
  • 388
  • 1
  • 7
  • 18

3 Answers3

3

Abstract or no, you're looking for an Inversion of Control (IoC) framework here, specifically one that lets you do method interception.

I'd look at Unity, or Spring. There are a few others out there.

kprobst
  • 16,165
  • 5
  • 32
  • 53
3

The best way to do this is as follows:

public abstract class MyClass {

    public void DoOuter() {
        FireEvent();
        DoInner();
    }

    protected abstract void DoInner();
}

When someone wants to call doInner they have to call DoOuter() in order to execute it. To specify functionality you override DoInner(). So FireEvent() is always called before whatever DoInner() functionality is specified... unless it gets called directly by a child class, which you can't really guard against.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
DJClayworth
  • 26,349
  • 9
  • 53
  • 79
2

Not really as an abstract method is always overidden and there is no guarantee that the override call base.Method() to an implementation of it.

Your best bet is to create a virtual method which raises the event and then make all your overrides call base.Method()

If you want to intercept the method call, here is a question about how to do that.

Community
  • 1
  • 1
Oskar Kjellin
  • 21,280
  • 10
  • 54
  • 93