繁体   English   中英

在switch语句中使用字符串集合

[英]using collection of strings in a switch statement

我正试图找到解决这个问题的方法。 这是我的示例代码:

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值,枚举将是完美的,但我没有找到与字符串相同的小解决方案。

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

在您的具体示例中轻松修复:

switch(Array.IndexOf(Commands, Command))
{
    case 0: ...  
    case 1: ...

    default: //unknown command. Technically, this is case -1
} 

其他替代品:

  1. 内联字符串。

    switch(命令){case“CommandOne”:... case“CommandTwo”:...}

  2. 正如KirkWoll所说,使用枚举。 这可能是最干净的解决方案。

  3. 在更复杂的场景中,使用诸如Dictionary<string, Action>Dictionary<string, Func<Foo>>类的查找可能提供更好的可表达性。

  4. 如果案例很复杂,您可以创建ICommand接口。 这将需要将命令字符串映射到正确的具体实现,您可以使用简单的构造(切换/字典)或花式反射(查找具有该名称的ICommand实现,或具有特定的属性修饰)。

就在昨天,我为它创建了一个解决方案。 在你的情况下, 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);
    }
}

您可以通过创建IYourCommand对象并将它们加载到Dictionary<string, IYourCommand>完全消除switch语句。

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();
}

我一般不喜欢这种东西的字符串 - 它很容易因拼写错误,不同的外壳等而陷入麻烦 - 但可能这就是你想要使用变量而不是字符串文字的原因。 如果枚举解决方案不合适,使用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
        }
    }
}

正如您所说,在交换机中只允许使用常量表达式。 您通常会通过定义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枚举值。

定义Dictionary<string, enum>并在输入开关之前将输入命令映射到适当的值。 如果未找到匹配,则发生默认处理。

你可以反过来实现目标。

使用Enum及其GetNames调用来获取循环的字符串数组。

Enum.GetNames(typeof (*YOURENUM*));

有关更多信息。 http://msdn.microsoft.com/en-us/library/system.enum.getnames.aspx

这里有很好的答案,可能比我要提到的更好地回答你的问题......

根据逻辑的复杂程度,您可以考虑使用如下策略模式:

重构一个Switch语句

要么

战略模板模式

再一次,很可能比你的解决方案问题更复杂,只是把它扔出去......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM