我正在努力寻找解决这个问题的方法。这是我的示例代码:
class Program
{
private string Command;
private static string[] Commands = { "ComandOne", "CommandTwo", "CommandThree", "CommandFour" };
static void Main(string[] args)
{
Command = args[0];
switch(Command)
{
case Commands[0]: //do something
break;
case Commands[1]: //do something else
break;
case Commands[2]: //do something totally different
break;
case Commands[3]: //do something boring
break;
default: //do your default stuff
break;
}
}
void DifferentMethod()
{
foreach(string c in Commands)
{
//do something funny
}
}
}
此代码不起作用,因为开关中的字符串值不是常量。我想编写易于维护的代码。
我喜欢使用数组之类的东西,因为我需要在循环中的其他地方使用相同的值。
对于 int 值,枚举将是完美的,但我没有找到使用字符串来解决相同问题的小解决方案。
Convert Commands
进入一个枚举:
enum Commands { ComandOne, CommandTwo, CommandThree, CommandFour }
Switch 语句应该如下所示:
static void Main(string[] args)
{
Command = (Commands)Enum.Parse(typeof(Commands), args[0]);
switch(Command)
{
case Commands.CommandOne:
//do something
break;
case Commands.CommandTwo:
//do something else
break;
...
default:
// default stuff
}
}
你的最后一个方法应该是这样的:
void DifferentMethod()
{
foreach(var c in Enum.GetValues(typeof(Commands)))
{
string s = c.ToString();
//do something funny
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)