将参数传递给Action?

时间:2011-12-19 15:14:57

标签: c# asp.net-mvc

我想完全理解如何简化以下内容:

    public ActionResult Create(string ds) {
            InitializeServices(ds, "0000");
            vm.Account = new Account {
                    PartitionKey = "0000",
                    RowKey = "0000",
                    Created = DateTime.Now,
                    CreatedBy = User.Identity.Name
            };
        }
        catch (ServiceException ex) {
            ModelState.Merge(ex.Errors);
        }
        catch (Exception e) {
            Trace.Write(e);
            ModelState.AddModelError("", "Database access error: " + e.Message);
        }
        return View("CreateEdit", vm);
    }

我有一些很好的答案,建议如下:

    private void HandleException(Action action) {
        try { 
            action(); 
        } 
        catch (ServiceException ex) { 
            ModelState.Merge(ex.Errors); 
        } 
        catch (Exception e) 
        { 
            Trace.Write(e); 
            ModelState.AddModelError("", "Database access error: " + e.Message); 
        } 
    } 

    RunAndHandleExceptions(new Action(() =>                 
   {                      
        //Do some computing                 }
    )); 

这看起来是一个非常好的解决方案,但我仍然不明白我是如何通过我的 参数进入动作。我需要做的是传递以下内容:

     string ds
     System.Web.Mvc.ModelState ModelState  (passed as a reference)

3 个答案:

答案 0 :(得分:2)

只是

 HandleException(() => someFunction(ds, ModeState));

应该这样做

要获得返回值,您需要Func<>,而不是Action<>

private TR HandleException<TR>(Func<TR> action)
{
    try
    {
        return action();
    }
    catch (ServiceException ex)
    {
        ModelState.Merge(ex.Errors);
    }
    catch (Exception e)
    {
        Trace.Write(e);
        ModelState.AddModelError("", "Database access error: " + e.Message);
    }

    return default(TR); // null for reference types
}

然后你会使用它,例如没有现有的功能:

bool result = HandleException(() =>
    {
         if (string.IsNullOrEmpty(ds))
             return false;

         // do interesting stuff that throws many kinds of exceptions :)
         // Note: freely use ds and ModelState from surrounding scope, 
         // no need to 'pass them'

         return true;
    });

答案 1 :(得分:0)

您可以定义一个最多包含16个参数的动作(如果该数字很有用,请不要讨论)。所以,酸性呼叫可能看起来像:

private void HandleException(Action<string, System.Web.Mvc.ModelState ModelState  > action) {

修改

以下是具有参数:

的操作的示例
private void RunHandleException(Action<int> action) 
{
    action(someIntValue);
}

...

RunAndHandleExceptions((someInt) => 
    {    
        //Do some computing      
    });  

这是一个函数具有返回值的示例:

private void RunHandleException(Func<bool, int> action) 
{
    bool returnValue = action(someIntValue);
}

...

RunAndHandleExceptions((someInt) => 
    {    
        //Do some computing  
        return true;    
    });  

答案 2 :(得分:0)

你看过RedirectToAction吗?

return this.RedirectToAction(c => c.SomeAction(MyParam));