繁体   English   中英

String上的C ++ / CLI开关

[英]C++/CLI switch on String

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

string val = GetVal();
switch(val)
{
case "val1":
  DoSomething();
  break;
case "val2":
default:
  DoSomethingElse();
  break;
}

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

System::String ^val = GetVal();
switch(val)  // Compile error
{
   // Snip
}

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

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

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

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

你肯定不能在C / C ++的switch语句中使用除整数之外的任何东西。 在C ++中执行此操作的最简单方法是使用if和else语句:

std::string val = getString();
if (val.equals("val1") == 0)
{
  DoSomething();
}
else if (val.equals("val2") == 0)
{
  DoSomethingElse();
}

编辑:

我刚刚发现你问过C ++ / CLI - 我不知道上面是否仍然适用; 它肯定在ANSI C ++中。

我想我在codeguru.com上找到了一个解决方案。

我知道我的答案有点太迟了,但我认为这也是一个很好的解决方案。

struct ltstr {
    bool operator()(const char* s1, const char* s2) const {
        return strcmp(s1, s2) < 0;
    }
};

std::map<const char*, int, ltstr> msgMap;

enum MSG_NAMES{
 MSG_ONE,
 MSG_TWO,
 MSG_THREE,
 MSG_FOUR
};

void init(){
msgMap["MSG_ONE"] = MSG_ONE;
msgMap["MSG_TWO"] = MSG_TWO;
}

void processMsg(const char* msg){
 std::map<const char*, int, ltstr>::iterator it = msgMap.find(msg);
 if (it == msgMap.end())
  return; //Or whatever... using find avoids that this message is allocated in the map even if not present...

 switch((*it).second){
  case MSG_ONE:
   ...
  break:

  case MSG_TWO:
  ...
  break;

 }
}

暂无
暂无

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

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