String上的C++/CLI开关

hea*_*vyd 3 .net string c++-cli switch-statement

在其他.NET语言(如C#)中,您可以打开字符串值:

string val = GetVal();
switch(val)
{
case "val1":
  DoSomething();
  break;
case "val2":
default:
  DoSomethingElse();
  break;
}
Run Code Online (Sandbox Code Playgroud)

在C++/CLI中似乎不是这种情况

System::String ^val = GetVal();
switch(val)  // Compile error
{
   // Snip
}
Run Code Online (Sandbox Code Playgroud)

是否有一个特殊的关键字或其他方式使其适用于C++/CLI,就像在C#中一样?

dil*_*ig0 5

实际上,如果测试对象定义了转换为整数,则可以使用除整数之外的任何内容(有时由整数类型指定).

String对象没有.

但是,您可以使用字符串键创建一个映射(检查比较是否已得到很好的处理)以及指向实现某些接口的类的指针:

class MyInterface {
  public:
    virtual void doit() = 0;
}

class FirstBehavior : public MyInterface {
  public:
    virtual void doit() {
      // do something
    }
}

class SecondBehavior : public MyInterface {
  public:
    virtual void doit() {
      // do something else
    }
}

...
map<string,MyInterface*> stringSwitch;
stringSwitch["val1"] = new FirstBehavior();
stringSwitch["val2"] = new SecondBehavior();
...

// you will have to check that your string is a valid one first...
stringSwitch[val]->doit();    
Run Code Online (Sandbox Code Playgroud)

实施有点长,但设计得很好.