根据anti-if campaign最好不要在我们的代码中使用 ifs。谁能告诉我是否可以摆脱这段代码中的 if ? (switch也不是一个选项,重点是去掉条件逻辑,而不是用类似的语言结构替换ifs)
if(s == "foo")
{
Writeln("some logic here");
}
else if(s == "bar")
{
Writeln("something else here");
}
else if(s == "raboof")
{
Writeln("of course I need more than just Writeln");
}
(语言:Java 或 C#)
最佳答案
这是一种方法... :)
delegate void DoStuff();
...
IDictionary<string, DoStuff> dict = new Dictionary<string, DoStuff>();
dict["foo"] = delegate { Console.WriteLine("some logic here"); };
dict["bar"] = delegate { Console.WriteLine("something else here"); };
dict["raboof"] = delegate { Console.WriteLine("of course I need more than just Writeln"); };
dict["foo"]();
关于java - 在不使用 "if"的情况下执行此操作 | if(s == "value1"){...} 否则 if(s == "value2") { ...},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1999282/