我知道有很多 delegate/func 示例,但我找不到任何适合我的示例,或者我就是不理解它们。
我正在为一个网站使用 asp.net MVC,该网站需要一些网络服务调用以供外部应用程序与我的应用程序交互。这些都需要一个函数来执行(去数据库等等),并且每次都返回一个相似的数据模型。我想将每个调用包装在 try/catch 中并填充模型。
这是每次调用都会发生的通用代码。
var model = new ResponseDataModel();
try
{
//execute different code here
}
catch (Exception ex)
{
model.Error = true;
model.Message = ex.ToString();
}
return View(model); // will return JSON or XML depending on what the caller specifies
这是我正在使用的 Controller 方法/功能之一
public ActionResult MillRequestCoil()
{
var model = new ResponseDataModel();
try
{
/* edit */
//specific code
string coilId = "CC12345";
//additional code
model.Data = dataRepository.doSomethingToCoil(coilId);
//replaced code
//model.Data = new { Coil = coilId, M3 = "m3 message", M5 = "m5 message" };
model.Message = string.Format("Coil {0} sent successfully", coilId);
}
catch (Exception ex)
{
model.Error = true;
model.Message = ex.ToString();
}
return View(model);
}
我希望能够以某种方式将特定函数转换为变量以传递到通用代码中。我看过委托(delegate)和匿名函数,但除非您自己动手做,否则它们会让人很困惑。
最佳答案
将以下内容放在可访问的地方:
public static ActionResult SafeViewFromModel(
Action<ResponseDataModel> setUpModel)
{
var model = new ResponseDataModel();
try
{
setUpModel(model);
}
catch (Exception ex)
{
model.Error = true;
model.Message = ex.ToString();
}
return View(model);
}
然后像这样调用它:
public ActionResult MillRequestCoil()
{
return MyHelperClass.SafeViewFromModel(model =>
{
string coilId = "CC12345";
model.Data = new {
Coil = coilId,
M3 = "m3 message",
M5 = "m5 message" };
model.Message = string.Format("Coil {0} sent successfully", coilId);
});
}
关于c# - 需要将函数包装在 c# 中的标准 try/catch 函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12265262/