c# - 需要将函数包装在 c# 中的标准 try/catch 函数中

标签 c# asp.net delegates anonymous-function

我知道有很多 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/

相关文章:

c# - 如何使用 TechTalk.SpecFlow 和 C# 以编程方式忽略某些验收测试?

c# - 如何知道c#中的循环持续时间

c# - 如何仅将文件夹中的某些图像显示到 ASP.NET 中的转发器中

c# - 如何在 ASP.NET Core 1.0 中为 Web 应用程序显示 LoggerFactory 日志控制台?

objective-c - 为什么 Objective-C 中会自动调用这个委托(delegate)方法?

c# - 从 F# 调用 C# 函数

c# - C# 中的不安全代码会导致内存损坏吗?

c# - 在 nodatime 上添加两个句点

oop - 我在哪里使用委托(delegate)?

ios - 堆叠式 UIViewController 中的 UITextView 委托(delegate)问题