Enum value to string

前端 未结 6 1926
无人共我
无人共我 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:33

    You're going about this backwards. Don't try to use dynamic strings as case labels (you can't), instead parse the string into an enum value:

    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");
        } 
    } 
    

    EDIT: In principle, you could just compare to hard-coded strings in your switch statements (see below), but this is the least advisable approach, since it will simply break when you change the values passed in to the method, or the definition of the enum. I'm adding this since it's worth knowing that strings can be used as case labels, so long as they are compile-time literals. Dynamic values can't be used as cases, since the compiler doesn't know about them.

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

提交回复
热议问题