Is there a general way to call another method whenever a method is called in C #

I have a method like this:

public Something MyMethod() { Setup(); Do something useful... TearDown(); return something; } 

The Setup and TearDown methods are in the base class.

The problem I am facing is that I have to write this type of method again with the calls to the Setup () method and TearDown () method.

EDIT: The difficult part of this method is that โ€œDoing something useful ...โ€ refers only to this method. This part is different for every method I create.

In addition, I can have MyMethod2, MyMethod3, in one class. In all cases, I would like to run setup and breaks

Is there an elegant way to do this without having to write it every time?

I may be delusional, but a way to add a method attribute and intercept a method call so that I can do something before and after the call?

+5
source share
2 answers

Use generics , lambdas and delegates :

 public SomeThing MyMethod() { return Execute(() => { return new SomeThing(); }); } public T Execute<T>(Func<T> func) { if (func == null) throw new ArgumentNullException("func"); try { Setup(); return func(); } finally { TearDown(); } } 
+2
source

Just implement this method in an abstract base class as follows:

 public Something MyMethod() { Setup(); DoSomethingUsefull(); TearDown(); return something; } protected abstract DoSomethingUsefull(); 

Now you need to override only one method in the inherited classes - DoSomethingUsefull ()

This is a template template template

+6
source

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


All Articles