枚举值为字符串

Pos*_*Guy 37 c#

有谁知道如何获取字符串的枚举值?

例:

private static void PullReviews(string action, HttpContext context)
{
    switch (action)
    {
        case ProductReviewType.Good.ToString():
            PullGoodReviews(context);
            break;
        case ProductReviewType.Bad.ToString():
            PullBadReviews(context);
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

当试图使用ToString(); 编译器抱怨因为case语句期望一个常量.我也知道ToString()是用intellisense中的一行打出来的

Ala*_*lan 39

是的,您可以使用.ToString()获取枚举的字符串值,但不能.ToString()在switch语句中使用.Switch语句需要常量表达式,而.ToString()直到运行时才会计算,因此编译器会抛出错误.

要获得所需的行为,只需稍微改变一下方法,就可以使用enum.Parse()action字符串转换为枚举值,然后切换该枚举值.从.NET 4开始,您可以使用Enum.TryParse()并预先进行错误检查和处理,而不是在交换机体中.

如果是我,我会将字符串解析为枚举值并打开它,而不是打开字符串.

private static void PullReviews(string action, HttpContext context)
{
    ProductReviewType review;

    //there is an optional boolean flag to specify ignore case
    if(!Enum.TryParse(action,out review))
    {
       //throw bad enum parse
    }


    switch (review)
    {
        case ProductReviewType.Good:
            PullGoodReviews(context);
            break;
        case ProductReviewType.Bad:
            PullBadReviews(context);
            break;
        default:
            //throw unhandled enum type
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你是downvote,请让我知道为什么,所以我可以解决任何错误.谢谢. (2认同)

LBu*_*kin 13

你正在倒退这个.不要尝试使用动态字符串作为案例标签(您不能),而是将字符串解析为枚举值:

private static void PullReviews(string action, HttpContext context) 
{ 
    // Enum.Parse() may throw if input is invalid, consider TryParse() in .NET 4
    ProductReviewType actionType = 
        (ProductReviewType)Enum.Parse(typeof(ProductReviewType), action);

    switch (actionType) 
    { 
        case ProductReviewType.Good: 
            PullGoodReviews(context); 
            break; 
        case ProductReviewType.Bad: 
            PullBadReviews(context); 
            break; 
        default: // consider a default case for other possible values...
            throw new ArgumentException("action");
    } 
} 
Run Code Online (Sandbox Code Playgroud)

编辑:原则上,您可以只比较switch语句中的硬编码字符串(见下文),但这是最不可取的方法,因为当您更改传入方法的值或定义时,它会简单地中断的枚举.我正在添加它,因为值得知道字符串可以用作案例标签,只要它们是编译时文字即可.动态值不能用作案例,因为编译器不知道它们.

// DON'T DO THIS...PLEASE, FOR YOUR OWN SAKE...
switch (action) 
{ 
    case "Good": 
        PullGoodReviews(context); 
        break; 
    case "Bad": 
        PullBadReviews(context); 
        break; 
} 
Run Code Online (Sandbox Code Playgroud)


sim*_*sjo 5

public enum Color
{
    Red
}

var color = Color.Red;
var colorName = Enum.GetName(color.GetType(), color); // Red
Run Code Online (Sandbox Code Playgroud)

编辑:或者你想要..

Enum.Parse(typeof(Color), "Red", true /*ignorecase*/); // Color.Red
Run Code Online (Sandbox Code Playgroud)

Enum没有TryParse,所以如果你期望错误,你必须使用try/catch:

try
{
  Enum.Parse(typeof(Color), "Red", true /*ignorecase*/);
}
catch( ArgumentException )
{
  // no enum found
}
Run Code Online (Sandbox Code Playgroud)