[英]Passing parameters to an anonymous method using an action in C#
將參數傳遞給操作仍然存在問題。 到目前為止,這里是:
public ActionResult Create(string ds) {
HandleException(new Action<string, ref System.Web.Mvc.ModelState>(ds,ModelState) => {
InitializeServices(ds, "0000");
vm.Account = new Account {
PartitionKey = "0000",
RowKey = "0000",
Created = DateTime.Now,
CreatedBy = User.Identity.Name
};
});
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);
}
}
這給出了12個語法錯誤,並且大多數都指向該行:
HandleException(new Action<string,
我們也有語法錯誤,說“ ref”不是正確的語法
public ActionResult Create(string ds) {
HandleException(() => {
InitializeServices(ds, "0000");
vm.Account = new Account {
PartitionKey = "0000",
RowKey = "0000",
Created = DateTime.Now,
CreatedBy = User.Identity.Name
};
});
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);
}
}
通用類型期望類型作為其參數...因此,Action需要每個參數的實際類型。 “參考類型”不是類型。 Ref只是一個關鍵字。
正如雅庫布(Jakub)所建議的,您應該完全刪除“ ref”並更改您的ModelState
HandleException
的參數的類型為Action
,但是您可以使用Action<string, ref System.Web.Mvc.ModelState>
類型的對象來調用它,這是Action<T1, T2>
。 這兩種類型必須相同,只需選擇其中一種即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.