I have this kind of code:
public class Foo
{
public SomeHandler OnBar;
public virtual void Bar()
{
}
}
Foo is a base class and therefor other classes might inherit from it.
I would like the OnBar
event to always be fired when Bar()
is called even if it's not called explicitly inside Bar.
How can it be done?
A common pattern is to have a non-virtual method that will do what you want that calls a virtual method. Subclasses can override the inner method to change the functionality, but the public method can be non-virtual on always raise the event first.
public class Foo
{
public SomeHandler OnBar;
public void Bar()
{
if (OnBar != null)
{
OnBar(this, EventArgs.Empty);
}
BarImpl();
}
protected virtual void BarImpl()
{
}
}
Short answer: you can't. Not with what Microsoft gives you out of the box.
That said, take a look at "aspect oriented programming" in .NET. Google that, you might get something useful.
Added: The standard way would be to raise the event in the Bar()
method and then require all derived classes to call the base implementation. But you can't enforce it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With