使用字符串的集合中switch语句 [英] using collection of strings in a switch statement

查看:128
本文介绍了使用字符串的集合中switch语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到这个问题的解决方案。这是我的例子code:

I'm trying to find a solution for this problem. This is my example code:

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
    }
  }
}

这code不起作用,因为在开关的字符串值不是常数。我想写易维护code。结果
我喜欢用像一个数组,因为我需要在一个循环的其他地方使用相同的值。结果
使用int值的枚举将是完美的,但我没有找到用绳子一样的东西小解决方案。

This code doesn't work because the string values in the switch are not constants. I want to write easy maintainable code.
I like to use something like an array because I need to use the same values somewhere else in a loop.
With int-values an enum would be perfect, but I didn't find a small solution for the same thing with strings.

推荐答案

转换命令成一个枚举:

enum Commands { ComandOne, CommandTwo, CommandThree, CommandFour }

switch语句应该是这样的:

Switch statement should look like:

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
    }
}

和您的最后一个方法应该是这样的:

And your last method should look like:

void DifferentMethod()
{
    foreach(var c in Enum.GetValues(typeof(Commands)))
    {
        string s = c.ToString(); 
        //do something funny
    }
}

这篇关于使用字符串的集合中switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆