C# asp.net mvc控制器中的封装开关逻辑
我尝试改进以下代码。问题是方法句柄变得很麻烦。我正在寻找一种从主方法中排除加法和处理命令的方法。我希望C# asp.net mvc控制器中的封装开关逻辑,c#,asp.net-mvc,refactoring,switch-statement,C#,Asp.net Mvc,Refactoring,Switch Statement,我尝试改进以下代码。问题是方法句柄变得很麻烦。我正在寻找一种从主方法中排除加法和处理命令的方法。我希望ActionResult HandleCommand方法通过添加新命令而不受更改的影响。所以,我对一个大的开关块不感兴趣。我很乐意收到任何建议 [HttpPost] public ActionResult HandleCommand(string command) { switch (command) { case
ActionResult HandleCommand
方法通过添加新命令而不受更改的影响。所以,我对一个大的开关块不感兴趣。我很乐意收到任何建议
[HttpPost]
public ActionResult HandleCommand(string command)
{
switch (command)
{
case "foo":
DoSomthing();
return View("someView1");
case "bar":
DoSomthingElse();
return RedirectToAction("someAction");
case "fooBar":
return File("file.txt", "application");
//...
default:
//...
return new HttpStatusCodeResult(404);
}
}
可以将您的方法重做为以下内容:
public ActionResult HandleCommand(string comand)
{
CommandAction Comand = commandHandler[comand] ?? new CommandAction(method, new HttpStatusCodeResult(404));
Comand.DoSomthing();
return Comand.Result;
}
如果您进行了一些更改:
public class CommandAction
{
public Action DoSomthing { get; set; }
public ActionResult Result { get; set; }
public CommandAction(Action action, ActionResult actionResult)
{
DoSomthing = action;
Result = actionResult;
}
}
public class SomeController : Controller
{
public Dictionary<string, CommandAction> commandHandler
{
get
{
return new Dictionary<string, CommandAction>()
{
{"foo", new CommandAction( DoSomthing, View("foo"))},
{"foo", new CommandAction( DoSomthingElse, RedirectToAction("someAction"))},
{"fooBar", new CommandAction( SomeMethod, File("file.txt", "application"))}
};
}
}
公共类命令操作
{
公共操作DoSomthing{get;set;}
公共操作结果{get;set;}
公共命令操作(操作操作,操作结果操作结果)
{
DoSomthing=行动;
结果=行动结果;
}
}
公共类控制器:控制器
{
公共字典命令处理程序
{
得到
{
返回新字典()
{
{“foo”,新的CommandAction(DoSomthing,View(“foo”)},
{“foo”,新的CommandAction(DoSomthingElse,RedirectToAction(“someAction”)},
{“fooBar”,新的CommandAction(SomeMethod,File(“File.txt”,“application”))}
};
}
}
而且,当您添加新命令ModifycommandHandler时,这就是我所看到的