Most likely I'll get negative answer here, but I'd like to ask my question.
Is there a way in C# to call the parent method before (or after) ANY child class method.
public class Base
{
protected static void ThisWillBeCalledBeforeAnyMethodInChild()
{
//do something, e.g. log
}
protected static void ThisWillBeCalledAFTERAnyMethodInChild()
{
//do something, e.g. log
}
}
public class SomeClass : Base
{
public static void SomeMethod1()
{
//Do something
}
public static void SomeMethod2()
{
//Do something
}
}
So, I want to method ThisWillBeCalledBeforeAnyMethodInChild
from Base class to run before SomeMethod1
or SomeMethod2
in SomeClass
. Similar with after method.
Is there any way to do it without calling methods with reflection?
So, aside from in your child method calling base.MethodNameYouWantToCall() before or after, you could take a different approach.
This is just an idea, and might not be what you're trying to achieve, but if I needed every child class to call parent functions before and after something I might do this:
class Parent
{
protected void Before() { /* does things */ }
protected void After() { /* does things */ }
abstract void OtherCode();
public void PubliclyExposedMethod {
Before();
OtherCode();
After();'
}
class Child : Parent {
OtherCode { Console.Write("Hello world"); }
}
In the above, the method you define in the child will be ran after the before method, and before the after. I think this is cleaner because it reduces the number of times you need to write base.()
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