在C#中执行嵌套if语句的更有效方法是什么
本文关键字:有效 方法 是什么 语句 if 执行 嵌套 | 更新日期: 2023-09-27 18:26:59
我有一个类似于下面所示的代码,我想知道是否有更有效的方法来用mvc编写这个方法。
public ActionResult LogViewerFiles([DataSourceRequest] DataSourceRequest request, string testValue, string testValue2)
{
if (string.IsNullOrWhiteSpace(testValue2) && string.IsNullOrWhiteSpace(testValue))
{
return View();
}
if (!string.IsNullOrWhiteSpace(testValue))
{
var fileName = testValue;
var logEntries = LogEntry.ReadLogEntries(fileName);
if (logEntries == null)
{
return JavaScript("Callback()");
}
return Json(logEntries.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
if (testValue2!= null)
{
var resultPath = testValue2;
var logEntriesArch = LogEntry.ReadLogEntries(resultPath);
return Json(logEntriesArch.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
return null;
}
基本上,我试图实现的是根据参数的值执行不同的if语句。在这种情况下,只有一个参数具有执行代码所需的信息,而另一个参数将始终为null。编写此方法是为了将收集到的所有信息显示在剑道剃刀网格中。
虽然这是一种过度处理(您的代码中确实存在设计问题),但您可以在调度器中重构代码。
请参阅此LINQPad示例:
public void Main()
{
Console.WriteLine(this.YourAction("foo", "bar"));
Console.WriteLine(this.YourAction("foo", "baz"));
}
public string YourAction(string firstParameter, string secondParameter)
{
var handler = Dispatcher.GetHandler(firstParameter, secondParameter);
if (handler == null)
{
throw new Exception("I don't know what to do.");
}
return handler.Handle(firstParameter, secondParameter);
}
public static class Dispatcher
{
private readonly static ICollection<Handler> Handlers = new List<Handler>();
static Dispatcher()
{
Handlers.Add(new FooHandler());
Handlers.Add(new BarHandler());
}
public static Handler GetHandler(string firstParameter, string secondParameter)
{
// Yes, Single, not First. If you screw up and two handlers can handle
// the same parameters set you want to know it up front, not later.
return Handlers.SingleOrDefault(a => a.CanHandle(firstParameter, secondParameter));
}
}
public abstract class Handler
{
public abstract bool CanHandle(string firstParameter, string secondParameter);
public abstract string Handle(string firstParameter, string secondParameter);
}
public class FooHandler : Handler
{
public override bool CanHandle(string firstParameter, string secondParameter)
{
return firstParameter == "foo" && secondParameter == "bar";
}
public override string Handle(string firstParameter, string secondParameter)
{
return "FooAction";
}
}
public class BarHandler : Handler
{
public override bool CanHandle(string firstParameter, string secondParameter)
{
return firstParameter == "foo" && secondParameter == "baz";
}
public override string Handle(string firstParameter, string secondParameter)
{
return "BarAction";
}
}
每个处理程序告诉调度程序它是否可以处理提供的参数,调度程序选择正确的参数,然后运行它