Run the method before and after the code

How can I copy some code in brackets to do the following?

MyCustomStatement(args){ // code goes here } 

Thus, before the code in brackets is executed, it will call the method, and when the code in brackets completes, it will call another method. Does something like this exist? I know this seems redundant for this when I can just call the methods before and after the code and that’s all, but I was just curious. I do not know how to say this because I am new to programming.

Thanks!

+4
source share
2 answers

You can do this by storing the code in an abstract class that executes the "before" and "after" code when you call Run() :

 public abstract class Job { protected virtual void Before() { // Executed before Run() } // Implement to execute code protected abstract void OnRun(); public void Run() { Before(); OnRun(); After(); } protected virtual void After() { // Executed after Run() } } public class CustomJob : Job { protected override void OnRun() { // Your code } } 

And in the calling code:

 new CustomJob().Run(); 

Of course, for each piece of custom code you will need to create a new class, which may be less desirable.

An easier way is to use Action :

 public class BeforeAndAfterRunner { protected virtual void Before() { // Executed before Run() } public void Run(Action actionToRun) { Before(); actionToRun(); After(); } protected virtual void After() { // Executed after Run() } } 

What can you name like this:

 public void OneOfYourMethods() { // your code } public void RunYourMethod() { new BeforeAndAfterRunner().Run(OneOfYourMethods); } 
+5
source

To literally achieve what you want, you can use the delegate:

 Action<Action> callWithWrap = f => { Console.WriteLine("Before stuff"); f(); Console.WriteLine("After stuff"); }; callWithWrap(() => { Console.WriteLine("This is stuff"); }); 

This requires adding “weird syntax” to your blocks and an understanding of how delegates and anonymous functions in C # work. Most often, if you are doing this in a class, use the technique demonstrated in @CodeCaster's answer.

+3
source

Source: https://habr.com/ru/post/1239057/


All Articles