Enum value to string

前端 未结 6 1879
无人共我
无人共我 2021-02-06 21:59

Does anyone know how to get enum values to string?

example:

private static void PullReviews(string action, HttpContext context)
{
    switch (action)
            


        
6条回答
  •  没有蜡笔的小新
    2021-02-06 22:45

    Yes, you can use .ToString() to get a string value for an enum, however you can't use .ToString() in a switch statement. Switch statements need constant expressions, and .ToString() does not evaluate until runtime, so the compiler will throw an error.

    To get the behavior you want, with a little change in the approach, you can use enum.Parse() to convert the action string to an enum value, and switch on that enum value instead. As of .NET 4 you can use Enum.TryParse() and do the error checking and handling upfront, rather than in the switch body.

    If it were me, I'd parse the string to an enum value and switch on that, rather than switching on the string.

    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
        }
    }
    

提交回复
热议问题