How to set space on Enum

后端 未结 14 1486
栀梦
栀梦 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:33

    Based on Smac's suggestion, I've added an extension method for ease, since I'm seeing a lot of people still having issues with this.

    I've used the annotations and a helper extension method.

    Enum definition:

    internal enum TravelClass
    {
        [Description("Economy With Restrictions")]
        EconomyWithRestrictions,
        [Description("Economy Without Restrictions")]
        EconomyWithoutRestrictions
    }
    

    Extension class definition:

    internal static class Extensions
    {
        public static string ToDescription(this Enum value)
        {
            FieldInfo field = value.GetType().GetField(value.ToString());
            DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
            return attribute == null ? value.ToString() : attribute.Description;
        }
    }
    

    Example using the enum:

    var enumValue = TravelClass.EconomyWithRestrictions;
    string stringValue = enumValue.ToDescription();
    

    This will return Economy With Restrictions.

    Hope this helps people out as a complete example. Once again, credit goes to Smac for this idea, I just completed it with the extension method.

提交回复
热议问题