3

在其他 .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# 中那样工作?

4

4 回答 4

5

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

字符串对象没有。

但是,您可以使用字符串键(检查比较是否处理良好)和指向将某些接口作为值实现的类的指针创建一个映射:

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

实现起来有点长,但设计得很好。

于 2009-06-24T13:25:53.373 回答
0

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

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

编辑:

我刚刚发现您询问了有关 C++/CLI 的问题——我不知道上述内容是否仍然适用;它在 ANSI C++ 中当然可以。

于 2009-06-23T22:28:02.010 回答
0

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

于 2009-08-10T08:55:54.110 回答
0

我知道我的回答来得太晚了,但我认为这也是一个很好的解决方案。

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;

 }
}
于 2009-12-05T10:04:24.120 回答