In my abstract class can I listen an abstract method and fire an event whenever that method is called? If yes how?
Asked
Active
Viewed 352 times
3 Answers
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
-
1This is actually a C# question, so I'm editing the answer a little, but the main idea is correct. – StriplingWarrior Aug 19 '11 at 19:30
-
D'oh. Thanks, StriplingWarrior. – DJClayworth Aug 19 '11 at 19:38
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