简体   繁体   中英

What is the best way to attach a label to an enum value

lets say I have an enum definition like so:

    public enum eCommentType
    {
        NormalComment = 0,
        OpenningComment = 1,
        StartProgressCommetn = 2,
        ClouserComment = 3,
        ReopennignComment = 4
    }

Now I want to present the enum option on a web page. I could just use a switch statement but then when i add a new value I will have to update my switch statement. What is the best way to append a label to each value or event better a resource id to support multilingual interface?

PS I use MVC for my current project but I would appreciate a general answer that could be used across many technologies ie a design pattern.

event better a resource id to support multilingual interface?

You can get Get text from resources

var text = normalComment.GetName();


public static class EnumExtension
{
        public static string GetName(this eCommentType type)
        {
            return Strings.ResourceManager.GetString(type.ToString());
        }
}

The to string return the name of the enum or you can use the tag [Description("yournamehere")] for every enum and use that

public enum eCommentType
{
    [Description("my super normal comment")]
    NormalComment = 0,
    [Description("my super opening comment")]
    OpenningComment = 1,
    [Description("etc")]
    StartProgressCommetn = 2,
    [Description("etc")]
    ClouserComment = 3,
    [Description("etc")]
    ReopennignComment = 4
}

in the .net world you could solve this by adding attributes to your enum and by implementing a custom type converter that could use a ressource id from an attribute to translate the corresponding enum value into localized text

this approach is basically the same as the one provided by Fabio Marcolini, except that a custom typeconverter will make the description localizable

If you need only descriptions of the items inside to show to a user, you can use:

Enum.GetValues , like :

var values = Enum.GetValues(typeof(eCommentType)); 

But still, MVC is not usually only about presentation, but also a binding between UI and a model, so usually you need to map values visible on the screen to actual values of eCommentType enum You will have to have some "mapper" that converts one data to another.

Yes, you can use also the same function that iterates over all available values and find requested one, after get's it's INT, but I would go for simple and clear switch/case , honestly, unless the enum values quantity becomes big.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM