请问,如何重构此代码以避免切换案例?我需要使用Dictionary吗?有没有办法在不添加新案例的情况下更改命令并自动生成...我的意思是这个解决方案不会取决于案例数量。我希望我的问题很清楚。
static void Main(string[] args)
{
ConsoleHelp ch1 = new ConsoleHelp();
Plus pl = new Plus();
Minus mn = new Minus();
Divide dv = new Divide();
Multiply mlt = new Multiply();
Sinus sin = new Sinus();
Tangent tan = new Tangent();
Square sq = new Square();
Degree dg = new Degree();
Percent pr = new Percent();
while (true)
{
Console.Write("command> ");
string com = Console.ReadLine();
if (com != null)
{
switch (com.ToLower())
{
case "?":
ch1.Helpper();
break;
case "plus":
pl.Sum();
break;
case "minus":
mn.Minusvalue();
break;
case "divide":
dv.Dividevalue();
break;
case "multiply":
mlt.Multvalue();
break;
case "sinus":
sin.Sinusvalue();
break;
case "tangent":
tan.Tangentvalue();
break;
case "square":
sq.Squarevalue();
break;
case "degree":
dg.Degvalue();
break;
case "percent":
pr.Pervalue();
break;
case "c":
Environment.Exit(0);
break;
default:
Console.WriteLine("The command is not supported. Enter one of the valid commands.");
break;
}
}
}
Console.ReadLine();
}
答案 0 :(得分:1)
可以做以下其中一项:
Dictionary<String, Action> myActions = new Dictionary<String, Action>() {
{"One", delegate { ActionA(); }},
{"Two", delegate { ActionB(); }},
{"Three", delegate { ActionC(); }},
{"Four", delegate { ActionD(); }}
};
myActions["StringInput"]();
定义字典时,请确保您可以访问外部类,以便可以关闭它们。
答案 1 :(得分:1)
看起来问题是“如何找到许多用于操作的命名处理程序”。
一些可能的选择:
[CustomCommand(Name="percent")]
答案 2 :(得分:1)
虽然在您的示例中使用switch
没有任何问题,但您可以使用Dictionary<string, action>
将命令映射到适当的操作:
static void Main(string[] args)
{
ConsoleHelp ch1 = new ConsoleHelp();
Plus pl = new Plus();
Minus mn = new Minus();
Divide dv = new Divide();
Multiply mlt = new Multiply();
Sinus sin = new Sinus();
Tangent tan = new Tangent();
Square sq = new Square();
Degree dg = new Degree();
Percent pr = new Percent();
var commands = new Dictionary<string, Action>(StringComparer.InvariantCultureIgnoreCase)
{
{ "?", ch1.Helper },
{ "plus", p1.Sum },
{ "minus", mn.MinusValue },
{ "divide", dv.DivideValue },
{ "multiply", mlt.Multvalue },
{ "sinus", sin.Sinusvalue },
{ "tangent", tan.Tangentvalue },
{ "square", sq.Squarevalue },
{ "degree", dg.Degvalue },
{ "percent", pr.Pervalue},
{ "c", () => Environment.Exit(0) }
};
while (true)
{
Console.Write("command> ");
string com = Console.ReadLine();
if (!String.IsNullOrEmpty(com))
{
Action action;
if(commands.TryGetValue(com))
action();
else
Console.WriteLine("The command is not supported. Enter one of the valid commands.");
}
}
}
答案 3 :(得分:0)
字典可以帮助你
var dic = new Dictionary<string, Action>();
dic.Add("divide", () => dv.Dividevalue());
var com = "div";
dic[com]();
当然,您必须检查命令是否已注册,可能是
Action action = null;
if (dic.TryGetValue(com, ou action))
{
action();
}