首页 > 解决方案 > 如何限制具有特定名称的字符串的值

问题描述

我想要一个限制为 4-5 个值的ex: "Insert", "update", "delete", "check"字符串(这些值之一是这样的:truefalsebool

//not what i want
switch(str){
case "update":
isgoodvul=true;
break;
case "delete":
//(and so on).....
}

但更像

//what i want
string limited="hello world";
//error;
string limited="update";
//not error;
string any_other_string_name_exept_limited="hello world";
//not error;
string any_other_string_name_exept_limited="update";
//not error;

标签: c#string

解决方案


您可以使用枚举来获得您想要的行为。定义这个:

enum MyAction
{
    insert = 0,
    update =1,
    delete = 2,
    check = 3
}

然后像这样使用它:

Enum action = MyAction.update;

switch(action){
  case(MyAction.insert)
    //Do insert
  case(MyAction.update)
    //Do update
...
}

推荐阅读