Generic Func<> as parameter to base method
- by WestDiscGolf
I might be losing the plot, but I hope someone can point me in the right direction.
What am I trying to do?
I'm trying to write some base methods which take Func< and Action so that these methods handle all of the exception handling etc. so its not repeated all over the place but allow the derived classes to specify what actions it wants to execute.
So far this is the base class.
public abstract class ServiceBase<T>
{
protected T Settings { get; set; }
protected ServiceBase(T setting)
{
Settings = setting;
}
public void ExecAction(Action action)
{
try
{
action();
}
catch (Exception exception)
{
throw new Exception(exception.Message);
}
}
public TResult ExecFunc<T1, T2, T3, TResult>(Func<T1, T2, T3, TResult> function)
{
try
{
/* what goes here?! */
}
catch (Exception exception)
{
throw new Exception(exception.Message);
}
}
}
I want to execute an Action in the following way in the derived class (this seems to work):
public void Delete(string application, string key)
{
ExecAction(() => Settings.Delete(application, key));
}
And I want to execute a Func in a similar way in the derived class but for the life of me I can't seem to workout what to put in the base class.
I want to be able to call it in the following way (if possible):
public object Get(string application, string key, int? expiration)
{
return ExecFunc(() => Settings.Get(application, key, expiration));
}
Am I thinking too crazy or is this possible? Thanks in advance for all the help.