How to set space on Enum

后端 未结 14 1387
栀梦
栀梦 2020-11-29 08:00

I want to set the space on my enum. Here is my code sample:

public enum category
{
    goodBoy=1,
    BadBoy
}

I want to set



        
相关标签:
14条回答
  • 2020-11-29 08:21

    Think this might already be covered, some suggestions:

    • How do I have an enum bound combobox with custom string formatting for enum values?
    • C# Getting Enum values

    Just can't beat stackoverflow ;) just sooo much on here nowdays.

    0 讨论(0)
  • 2020-11-29 08:22

    You are misunderstanding what an enum is used for. An enum is for programming purposes, essentially giving a name to a number. This is for the programmer's benefit while reading the source code.

    status = StatusLevel.CRITICAL; // this is a lot easier to read...
    status = 5;                    // ...than this
    

    Enums are not meant for display purposes and should not be shown to the end user. Like any other variable, enums cannot use spaces in the names.

    To associate internal values with "pretty" labels you can display to a user, can use a dictionary or hash.

    myDict["Bad Boy"] = "joe blow";
    
    0 讨论(0)
  • 2020-11-29 08:26

    Since the original question was asking for adding a space within the enum value/name, I would say that the underscore character should be replaced with a space, not an empty string. However, the best solution is the one using annotations.

    0 讨论(0)
  • 2020-11-29 08:27

    That's not possible, an enumerator cannot contain white space in its name.

    0 讨论(0)
  • 2020-11-29 08:27

    C# now has a built in function to get the description from an enum. Here's how it works

    My Enum:

    using System.ComponentModel.DataAnnotations;
    
    public enum Boys
    {
    [Description("Good Boy")]
    GoodBoy = 1,
    [Description("Bad Boy")]
    BadBoy = 2
    }
    

    This is how to retrieve the description in code

    var enumValue = Boys.GoodBoy;
    string stringValue = enumValue.ToDescription();
    

    Result is : Good Boy.

    0 讨论(0)
  • 2020-11-29 08:30

    Why don't you use ToString() ?

    I mean that when use ToString(),it gives the enum value. Just you have to add some identifier to catch space.For example:

    public enum category
    {
       good_Boy=1,
       Bad_Boy
    }
    

    When you get an enum in codes like category a = ..., you can use ToString() method. It gives you value as a string. After that, you can simply change _ to empty string.

    0 讨论(0)
提交回复
热议问题