Enum ToString with user friendly strings

后端 未结 23 1783
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 11:44

My enum consists of the following values:

private enum PublishStatusses{
    NotCompleted,
    Completed,
    Error
};

I want to be able to

相关标签:
23条回答
  • 2020-11-22 12:36

    That other post is Java. You can't put methods in Enums in C#.

    just do something like this:

    PublishStatusses status = ...
    String s = status.ToString();
    

    If you want to use different display values for your enum values, you could use Attributes and Reflection.

    0 讨论(0)
  • 2020-11-22 12:38

    I use the Description attribute from the System.ComponentModel namespace. Simply decorate the enum:

    private enum PublishStatusValue
    {
        [Description("Not Completed")]
        NotCompleted,
        Completed,
        Error
    };
    

    Then use this code to retrieve it:

    public static string GetDescription<T>(this T enumerationValue)
        where T : struct
    {
        Type type = enumerationValue.GetType();
        if (!type.IsEnum)
        {
            throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
        }
    
        //Tries to find a DescriptionAttribute for a potential friendly name
        //for the enum
        MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
        if (memberInfo != null && memberInfo.Length > 0)
        {
            object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
    
            if (attrs != null && attrs.Length > 0)
            {
                //Pull out the description value
                return ((DescriptionAttribute)attrs[0]).Description;
            }
        }
        //If we have no description attribute, just return the ToString of the enum
        return enumerationValue.ToString();
    }
    
    0 讨论(0)
  • 2020-11-22 12:38

    The simplest way is just to include this extension class into your project, it will work with any enum in the project:

    public static class EnumExtensions
    {
        public static string ToFriendlyString(this Enum code)
        {
            return Enum.GetName(code.GetType(), code);
        }
    }
    

    Usage:

    enum ExampleEnum
    {
        Demo = 0,
        Test = 1, 
        Live = 2
    }
    

    ...

    ExampleEnum ee = ExampleEnum.Live;
    Console.WriteLine(ee.ToFriendlyString());
    
    0 讨论(0)
  • 2020-11-22 12:39

    I created a reverse extension method to convert the description back into an enum value:

    public static T ToEnumValue<T>(this string enumerationDescription) where T : struct
    {
        var type = typeof(T);
    
        if (!type.IsEnum)
            throw new ArgumentException("ToEnumValue<T>(): Must be of enum type", "T");
    
        foreach (object val in System.Enum.GetValues(type))
            if (val.GetDescription<T>() == enumerationDescription)
                return (T)val;
    
        throw new ArgumentException("ToEnumValue<T>(): Invalid description for enum " + type.Name, "enumerationDescription");
    }
    
    0 讨论(0)
  • 2020-11-22 12:39
    public enum MyEnum
    {
        [Description("Option One")]
        Option_One
    }
    
    public static string ToDescriptionString(this Enum This)
    {
        Type type = This.GetType();
    
        string name = Enum.GetName(type, This);
    
        MemberInfo member = type.GetMembers()
            .Where(w => w.Name == name)
            .FirstOrDefault();
    
        DescriptionAttribute attribute = member != null
            ? member.GetCustomAttributes(true)
                .Where(w => w.GetType() == typeof(DescriptionAttribute))
                .FirstOrDefault() as DescriptionAttribute
            : null;
    
        return attribute != null ? attribute.Description : name;
    }
    
    0 讨论(0)
提交回复
热议问题