I would like to provide encapsulation of actions/methods generically. I think this should be possible in C# but I’m not able to produce it so it compiles…
The following briefly demonstrates what I want. Is this possible somehow, perhaps by generalizing the class?
Required is:
- I want to execute the function/action (see method type) and ‘do something’ when an error occurs
- I want to return the value of the function if the method is a function (otherwise return
voidif possible) -
I want to ‘do something’ if the return type of the function is a
booleanand the value isfalse.public class Encapsulator { private Action _action; private Func<T> _function; private MethodType _type; //Action || Function public Encapsulator(Action action) { this._action = action; this._type = MethodType.Action; } public Encapsulator(Func<T> func) { //This is not accepted this._function = func; this._type = MethodType.Function; } public void Execute() { try { this._action(); } catch(Exception ex) { //do something throw; } } public T Execute<T>() { try { var r = this._function(); if(typeof(r) == bool) { if(!r) //do something } return r; } catch(Exception ex) { //do something throw; } } }
New Approach: The action Encapsulator will now return a dummy result (always true).
Calling the code: