異なる署名を持つ複数のメソッドがあり、それぞれのメソッドにカスタムログ例外を含むtry-catchブロックがあります。 (複数のコントローラで同じ構造)。C#パラメータとしての機能 - メソッドの構造を繰り返す
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");
}
}
私は
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);
}
}
¿私はそれをどのように行うことができ、他のすべてのメソッドのtry-catchブロックを回避し、実行するための方法がありますかしら?私は代理人を使用している例を見てきましたが、それは強く型付けされていることを理解しています。ありがとう!
奇妙な構成の構文を解析できません。 'ActionWithTryCatch'の中で、' del.Invoke() 'が' One() 'と' service.MethodTwo(param3、param4);で 'service.MethodOne(param1、param2);を実行するようにしたいのですか? 'Two()'で? –
もしそうなら、簡単です: 'public ActionResult ActionWithTryCatch(action act、String viewName){try {act();例えば、ActionWithTryCatch(()=> service.MethodTwo(param3、param4)、 "ViewName2"); –
として呼び出すか、あるいは 'public ActionResult ActionWithTryCatch(Func del 、string viewName) '? ( 'return del.Invoke();'デリゲートは 'ActionResult'を返すようです)... –