在一个参数中组合Action和Func

Ily*_*dik 7 .net c# delegates action func

我有很多方法需要一些具有相同模式的日志记录.有些方法需要返回一些值,有些则不需要.我已经创建了一个带有Action参数的方法,以避免对所有逻辑进行复制.它看起来像这样:

private void Execute(Action action)
{
   Logger.Start();
   try
   {
      action();
   }
   catch(Exception exception)
   {
      Logger.WriteException();
      throw;
   }
   finally
   {
       Logger.Finish();
   }
}
Run Code Online (Sandbox Code Playgroud)

现在我有一些类似的电话

public void DoSomething(string parameter)
{
    Execute(() => GetProvider(parameter).DoSomething());
}
Run Code Online (Sandbox Code Playgroud)

但我需要一些返回值的函数.最好的方法是什么?我现在找到了两个:

1)使用Func创建Execute方法的副本

private T Execute<T>(Func<T> action)
{
   Logger.Start();
   try
   {
      return action();
   }
   catch(Exception exception)
   {
      Logger.WriteException();
      throw;
   }
   finally
   {
       Logger.Finish();
   }
}
Run Code Online (Sandbox Code Playgroud)

此方法有效,但也有一些复制粘贴.

2)将参数欺骗为动作:

public Result DoSomething(string parameter)
{
    Result result = null;
    Execute(() => result = GetProvider(parameter).DoSomething());
    return result;
}
Run Code Online (Sandbox Code Playgroud)

这不需要复制粘贴,但看起来不太好.

有没有办法以某种方式加入Action和Func以避免任何这些方法,或者可能有另一种方法来实现相同的结果?

Jon*_*eet 6

第三种选择仍然是重载Execute,但使Action版本在版本方面起作用Func:

private void Execute(Action action)
{
    // We just ignore the return value here
    Execute(() => { 
        action();
        return 0; 
    });
}
Run Code Online (Sandbox Code Playgroud)

当然,如果这一切会更简单void更像是一个"真正的"类型(如Unit在F#等),在这一点上,我们可以只是Task<T>代替TaskTask<T>,以及...