【发布时间】:2016-08-31 18:39:46
【问题描述】:
我有多个具有不同签名的方法,每个方法都有一个带有自定义日志异常的 try-catch 块。 (多个控制器上的结构相同)。
public class TestController : BaseController
{
public static ActionResult One(int param1, string param2)
{
try
{
// Do something
}
catch (Exception e)
{
LogException(e.Message);
AddModelError(e.Message);
}
return View("ViwName1");
}
public static ActionResult Two(Date param3, bool param4)
{
try
{
// Do something
}
catch (Exception e)
{
LogException(e.Message);
AddModelError(e.Message);
}
return View("ViwName2");
}
}
我想知道是否有一种方法可以避免每个方法的 try-catch 阻塞并执行另一个
public class TestController : BaseController
{
public static ActionResult One(int param1, string param2)
{
// Do something (*)
// Call "ActionWithTryCatch" method that has a "function argument" to "Do something (*)"
}
public ActionResult ActionWithTryCatch(MyDelegate del, string viewName)
{
try
{
return del.Invoke();
}
catch (Exception e)
{
LogException(e.Message);
AddModelError(e.Message);
}
return View(viewName);
}
}
¿我该怎么做?我见过使用委托的例子,但我知道这是强类型的,所以没有找到办法做到这一点。谢谢!
【问题讨论】:
-
我无法解析你奇怪的编造语法。你是说在
ActionWithTryCatch内部,你想让del.Invoke()在One()中执行service.MethodOne(param1, param2);,在service.MethodTwo(param3, param4);中执行service.MethodTwo(param3, param4);? -
如果是这样,简单:
public ActionResult ActionWithTryCatch(Action act, String viewName) { try { act(); } catch (Exception ex){...等。调用为ActionWithTryCatch(() => service.MethodTwo(param3, param4), "ViewName2"); -
或者
public ActionResult ActionWithTryCatch(Func<ActionResult> del, string viewName)? (基于return del.Invoke();委托似乎返回ActionResult)... -
旁注:动作过滤器可以更好地解决您的实际问题...
-
哎呀——我的建议应该是
Func<ActionResult>/return act();,对不起
标签: javascript c# .net asp.net-mvc delegates