有没有办法使用一种方法来处理其他方法以避免代码重复?

时间:2010-04-15 14:28:00

标签: c# .net design-patterns

我想知道是否有一种编写方法或类的方法可以在任何方法中添加一些在许多方法之间共享的代码。这些方法返回不同的东西,其中一些只是无效。

以下是方法中重复的代码的一部分。

StartTimer(MethodBase.GetCurrentMethod().Name);
try
{
    // Actual method body
}
catch (Exception ex)
{
    bool rethrow = ExceptionPolicy.HandleException(ex, "DALPolicy");
    if (rethrow)
    {
         throw;
    }
}
finally
{
    StopTimer(MethodBase.GetCurrentMethod().Name);
}

非常感谢任何帮助。


Nix解决方案应用于上述代码

public T WrapMethod<T>(Func<T> func)
{
    StartTimer(func.Method.Name);
    try
    {
        return func();
    }
    catch (Exception ex)
    {
        bool rethrow = ExceptionPolicy.HandleException(ex, "DALPolicy");
        if (rethrow)
        {
            throw;
        }
    }
    finally
    {
        StopTimer(func.Method.Name);
    }
    return default(T);
}

3 个答案:

答案 0 :(得分:5)

我实际上有同样的问题......

C# searching for new Tool for the tool box, how to template this code

public Result<Boolean> CreateLocation(LocationKey key)
{
    LocationDAO locationDAO = new LocationDAO();
    return WrapMethod(() => locationDAO.CreateLocation(key));
}


public Result<Boolean> RemoveLocation(LocationKey key)
{
    LocationDAO locationDAO = new LocationDAO();
    return WrapMethod(() =>  locationDAO.RemoveLocation(key));
}


static Result<T> WrapMethod<T>(Func<Result<T>> func)
{
    try
    {
        return func();
    }
    catch (UpdateException ue)
    {
        return new Result<T>(default(T), ue.Errors);
    }
}

答案 1 :(得分:2)

这通常是通过面向方面编程完成的,据我所知,目前在.NET框架(或C#)中没有支持此功能。请参阅this post

另外,据我所知 - 没有自己做任何测试 - 似乎frameworks基于ContextBoundObject类为.NET提供AOP功能会产生很多性能开销,所以在决定易用性的优势是否大于性能劣势时,您可能希望考虑这一点。

答案 2 :(得分:1)

您可以使用委托和通用委托(例如public delegate T Func<T>();)传递要包装的代码。在下面的例子中,我需要类似的东西,我希望我的重试逻辑可以在许多场景中重用。在开头的示例中,您将看到如何使用它来传递我的匿名委托:

public class RetryOnError
{
    static void Example()
    {
      string endOfLineChar = Environment.NewLine;
      RetryOnError.RetryUntil<string>(delegate()
      {
          //attempt some potentially error throwing operations here

          //you can access local variables declared outside the the Retry block:
          return "some data after successful processing" + endOfLineChar;
      },
      new RetryOnError.OnException(delegate(ref Exception ex, ref bool rethrow)
      {
          //respond to the error and
          //do some analysis to determine if a retry should occur
          //perhaps prompting the user to correct a problem with a retry dialog
          bool shouldRetry = false;

          //maybe log error
          log4net.Error(ex);

          //maybe you want to wrap the Exception for some reason
          ex = new Exception("An unrecoverable failure occurred.", ex);
          rethrow = true;//maybe reset stack trace

          return shouldRetry;//stop retrying, normally done conditionally instead
      }));
    }

  /// <summary>
  /// A delegate that returns type T
  /// </summary>
  /// <typeparam name="T">The type to be returned.</typeparam>
  /// <returns></returns>
  public delegate T Func<T>();

  /// <summary>
  /// An exception handler that returns false if Exception should be propogated
  /// or true if it should be ignored.
  /// </summary>
  /// <returns>A indicater of whether an exception should be ignored(true) or propogated(false).</returns>
  public delegate bool OnException(ref Exception ex, ref bool rethrow);

  /// <summary>
  /// Repeatedly executes retryThis until it executes successfully with
  /// an exception, maxTries is reached, or onException returns false.
  /// If retryThis is succesful, then its return value is returned by RetryUntil.
  /// </summary>
  /// <typeparam name="T">The type returned by retryThis, and subsequently returned by RetryUntil</typeparam>
  /// <param name="retryThis">The delegate to be called until success or until break condition.</param>
  /// <param name="onException">Exception handler that can be implemented to perform logging,
  /// notify user, and indicates whether retrying should continue.  Return of true indicates
  /// ignore exception and continue execution, and false indicates break retrying and the
  /// exception will be propogated.</param>
  /// <param name="maxTries">Once retryThis has been called unsuccessfully <c>maxTries</c> times, then the exception is propagated.
  /// If maxTries is zero, then it will retry forever until success.
  /// </param>
  /// <returns>The value returned by retryThis on successful execution.</returns>
  public static T RetryUntil<T>(Func<T> retryThis, OnException onException, int maxTries)
  {
    //loop will run until either no exception occurs, or an exception is propogated(see catch block)
    int i = 0;
    while(true)
    {
      try
      {
        return retryThis();
      }
      catch ( Exception ex )
      {
        bool rethrow =false;//by default don't rethrow, just throw; to preserve stack trace
        if ( (i + 1) == maxTries )
        {//if on last try, propogate exception
          throw;
        }
        else if (onException(ref ex, ref rethrow))
        {
          if (maxTries != 0)
          {//if not infinite retries
            ++i;
          }
          continue;//ignore exception and continue
        }
        else
        {
          if (rethrow)
          {
            throw ex;//propogate exception
          }
          else
          {//else preserve stack trace
            throw;
          }
        }
      }
    }
  }

  /// <summary>
  /// Repeatedly executes retryThis until it executes successfully with
  /// an exception, or onException returns false.
  /// If retryThis is succesful, then its return value is returned by RetryUntil.
  /// This function will run infinitly until success or onException returns false.
  /// </summary>
  /// <typeparam name="T">The type returned by retryThis, and subsequently returned by RetryUntil</typeparam>
  /// <param name="retryThis">The delegate to be called until success or until break condition.</param>
  /// <param name="onException">Exception handler that can be implemented to perform logging,
  /// notify user, and indicates whether retrying should continue.  Return of true indicates
  /// ignore exception and continue execution, and false indicates break retrying and the
  /// exception will be propogated.</param>
  /// <returns></returns>
  public static T RetryUntil<T>(Func<T> retryThis, OnException onException)
  {
    return RetryUntil<T>(retryThis, onException, 0);
  }
}