Art*_*tur 5 .net c# 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);
}
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激.
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);
}
Run Code Online (Sandbox Code Playgroud)
我实际上有同样的问题....
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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
202 次 |
| 最近记录: |