我正在尝试找到解决此问题的方法。这是我的示例代码:
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
}
}
}
此代码不起作用,因为switch中的字符串值不是常量。我想编写易于维护的代码 我喜欢使用像数组这样的东西,因为我需要在循环中的其他地方使用相同的值 使用int值,枚举将是完美的,但我没有找到与字符串相同的小解决方案。
答案 0 :(得分:19)
将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
}
}
答案 1 :(得分:8)
特定示例中的一个简单修复:
switch(Array.IndexOf(Commands, Command))
{
case 0: ...
case 1: ...
default: //unknown command. Technically, this is case -1
}
其他替代方案:
内联字符串。
开关(命令) { 案例“CommandOne”:...... 案例“CommandTwo”:...... }
使用枚举,正如KirkWoll所说。这可能是最干净的解决方案。
在更复杂的情况下,使用Dictionary<string, Action>
或Dictionary<string, Func<Foo>>
等查询可能会提供更好的表达能力。
如果案例很复杂,您可以创建ICommand
界面。这需要将命令字符串映射到正确的具体实现,为此您使用简单的构造(切换/字典)或花式反射(使用该名称查找ICommand
实现,或者使用特定的属性修饰)。 / p>
答案 2 :(得分:5)
就在昨天我为它创建了一个解决方案。在你的情况下enum
更好,但这是我对一般非常规开关情况的解决方案。
用途:
static string DigitToStr(int i)
{
return i
.Case(1, "one")
.Case(2, "two")
.Case(3, "three")
.Case(4, "four")
.Case(5, "five")
.Case(6, "six")
.Case(7, "seven")
.Case(8, "eight")
.Case(9, "nine")
.Default("");
}
int a = 1, b = 2, c = 3;
int d = (4 * a * c - b * 2);
string res = true
.Case(d < 0, "No roots")
.Case(d == 0, "One root")
.Case(d > 0, "Two roots")
.Default(_ => { throw new Exception("Impossible!"); });
string res2 = d
.Case(x => x < 0, "No roots")
.Case(x => x == 0, "One root")
.Case(x => x > 0, "Two roots")
.Default(_ => { throw new Exception("Impossible!"); });
string ranges = 11
.Case(1, "one")
.Case(2, "two")
.Case(3, "three")
.Case(x => x >= 4 && x < 10, "small")
.Case(10, "ten")
.Default("big");
定义:
class Res<O, R>
{
public O value;
public bool succ;
public R result;
public Res()
{
}
static public implicit operator R(Res<O, R> v)
{
if (!v.succ)
throw new ArgumentException("No case condition is true and there is no default block");
return v.result;
}
}
static class Op
{
static public Res<O, R> Case<O, V, R>(this Res<O, R> o, V v, R r)
{
if (!o.succ && Equals(o.value, v))
{
o.result = r;
o.succ = true;
}
return o;
}
static public Res<O, R> Case<O, V, R>(this O o, V v, R r)
{
return new Res<O, R>()
{
value = o,
result = r,
succ = Equals(o, v),
};
}
static public Res<O, R> Case<O, R>(this Res<O, R> o, Predicate<O> cond, R r)
{
if (!o.succ && cond(o.value))
{
o.result = r;
o.succ = true;
}
return o;
}
static public Res<O, R> Case<O, R>(this O o, Predicate<O> cond, R r)
{
return new Res<O, R>()
{
value = o,
result = r,
succ = cond(o),
};
}
private static bool Equals<O, V>(O o, V v)
{
return o == null ? v == null : o.Equals(v);
}
static public R Default<O, R>(this Res<O, R> o, R r)
{
return o.succ
? o.result
: r;
}
static public R Default<O, R>(this Res<O, R> o, Func<O, R> def)
{
return o.succ ? o.result : def(o.value);
}
}
答案 3 :(得分:5)
您可以通过创建switch
个对象并将其加载到IYourCommand
来完全删除Dictionary<string, IYourCommand>
语句。
class Program
{
private Dictionary<string, IYourCommand> Command = new Dictionary<string, IYourCommand>
{
{ "CommandOne", new CommandOne() },
{ "CommandTwo", new CommandTwo() },
{ "CommandThree", new CommandThree() },
{ "CommandFour", new CommandFour() },
};
public static void Main(string[] args)
{
if (Command.ContainsKey(args[0]))
{
Command[args[0]].DoSomething();
}
}
}
public interface IYourCommand
{
void DoSomething();
}
答案 4 :(得分:3)
我一般不喜欢这种东西的字符串 - 它很容易因拼写错误,不同的外壳等而陷入麻烦 - 但可能这就是你想要使用变量而不是字符串文字的原因。如果枚举解决方案不合适,使用consts应该可以实现您的目标。
编辑:2013年10月28日修正错误的作业
class Program
{
private string Command;
const string command1 = "CommandOne";
const string command2 = "CommandTwo";
const string command3 = "CommandThree";
const string command4 = "CommandFour";
private static string[] Commands = { command1, command2, command3, command4 };
static void Main(string[] args)
{
string Command = args[0];
switch (Command)
{
case command1: //do something
break;
case command2: //do something else
break;
case command3: //do something totally different
break;
case command4: //do something boring
break;
default: //do your default stuff
break;
}
}
void DifferentMethod()
{
foreach (string c in Commands)
{
//do something funny
}
}
}
答案 5 :(得分:2)
正如您所说,交换机中只允许使用常量表达式。您通常会通过定义enum
并在交换机中使用它来执行此操作。
class Program
{
private enum Command
{
CommandOne = 1,
CommandTwo = 2,
CommandThree = 3
}
static void Main(string[] args)
{
var command = Enum.Parse(typeof(Commands), args[0]);
switch(command )
{
case Command.CommandOne: //do something
break;
case Command.CommandTwo: //do something else
break;
case Command.CommandThree: //do something totally different
break;
default: //do your default stuff
break;
}
}
}
使用Enum.GetValues
枚举DifferentMethod
中的枚举值。
答案 6 :(得分:2)
定义Dictionary<string, enum>
并在输入开关之前将输入命令映射到适当的值。如果未找到匹配,则会发生默认处理。
答案 7 :(得分:1)
你可以反过来实现目标。
使用Enum及其GetNames调用来获取要循环的字符串数组。
Enum.GetNames(typeof (*YOURENUM*));
了解更多信息。 http://msdn.microsoft.com/en-us/library/system.enum.getnames.aspx
答案 8 :(得分:1)
这里有很好的答案,可能比我要提及的更好地回答你的问题...
根据逻辑的复杂程度,您可以考虑使用这样的策略模式:
Refactoring a Switch statement
或
同样,很可能比你的解决方案要求更复杂,只是把它扔出去......