Enum ToString with user friendly strings

后端 未结 23 1782
伪装坚强ぢ
伪装坚强ぢ 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:16

    I think the best (and easiest) way to solve your problem is to write an Extension-Method for your enum:

    public static string GetUserFriendlyString(this PublishStatusses status)
        {
    
        }
    
    0 讨论(0)
  • 2020-11-22 12:19

    Clean summary of the above suggestions with sample:

    namespace EnumExtensions {
    
    using System;
    using System.Reflection;
    
    public class TextAttribute : Attribute {
       public string Text;
       public TextAttribute( string text ) {
          Text = text;
       }//ctor
    }// class TextAttribute
    
    public static class EnumExtender {
    
    public static string ToText( this Enum enumeration ) {
    
       MemberInfo[] memberInfo = enumeration.GetType().GetMember( enumeration.ToString() );
    
       if ( memberInfo != null && memberInfo.Length > 0 ) {
    
          object[] attributes = memberInfo[ 0 ].GetCustomAttributes( typeof(TextAttribute),  false );
    
          if ( attributes != null && attributes.Length > 0 ) {
             return ( (TextAttribute)attributes[ 0 ] ).Text;
          }
    
       }//if
    
       return enumeration.ToString();
    
    }//ToText
    
    }//class EnumExtender
    
    }//namespace
    

    USAGE:

    using System;
    using EnumExtensions;
    
    class Program {
    
    public enum Appearance {
    
      [Text( "left-handed" ) ]
      Left,
    
      [Text( "right-handed" ) ]
      Right,
    
    }//enum
    
    static void Main( string[] args ) {
    
       var appearance = Appearance.Left;
       Console.WriteLine( appearance.ToText() );
    
    }//Main
    
    }//class
    
    0 讨论(0)
  • 2020-11-22 12:19

    If you want something completely customizable, try out my solution here:

    http://www.kevinwilliampang.com/post/Mapping-Enums-To-Strings-and-Strings-to-Enums-in-NET.aspx

    Basically, the post outlines how to attach Description attributes to each of your enums and provides a generic way to map from enum to description.

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

    I use a generic class to store the enum/description pairs and a nested helper class to get the description.

    The enum:

    enum Status { Success, Fail, Pending }
    

    The generic class:

    Note: Since a generic class cannot be constrained by an enum I am constraining by struct instead and checking for enum in the constructor.

    public class EnumX<T> where T : struct
    {
        public T Code { get; set; }
        public string Description { get; set; }
    
        public EnumX(T code, string desc)
        {
            if (!typeof(T).IsEnum) throw new NotImplementedException();
    
            Code = code;
            Description = desc;
        }
    
        public class Helper
        {
            private List<EnumX<T>> codes;
    
            public Helper(List<EnumX<T>> codes)
            {
                this.codes = codes;
            }
    
            public string GetDescription(T code)
            {
                EnumX<T> e = codes.Where(c => c.Code.Equals(code)).FirstOrDefault();
                return e is null ? "Undefined" : e.Description;
            }
        }
    }
    

    Usage:

    EnumX<Status>.Helper StatusCodes = new EnumX<Status>.Helper(new List<EnumX<Status>>()
            {
                new EnumX<Status>(Status.Success,"Operation was successful"),
                new EnumX<Status>(Status.Fail,"Operation failed"),
                new EnumX<Status>(Status.Pending,"Operation not complete. Please wait...")
            });
    
            Console.WriteLine(StatusCodes.GetDescription(Status.Pending));
    
    0 讨论(0)
  • 2020-11-22 12:22

    For flags enum including.

        public static string Description(this Enum value)
        {
            Type type = value.GetType();
    
            List<string> res = new List<string>();
            var arrValue = value.ToString().Split(',').Select(v=>v.Trim());
            foreach (string strValue in arrValue)
            {
                MemberInfo[] memberInfo = type.GetMember(strValue);
                if (memberInfo != null && memberInfo.Length > 0)
                {
                    object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
    
                    if (attrs != null && attrs.Length > 0 && attrs.Where(t => t.GetType() == typeof(DescriptionAttribute)).FirstOrDefault() != null)
                    {
                        res.Add(((DescriptionAttribute)attrs.Where(t => t.GetType() == typeof(DescriptionAttribute)).FirstOrDefault()).Description);
                    }
                    else
                        res.Add(strValue);
                }
                else
                    res.Add(strValue);
            }
    
            return res.Aggregate((s,v)=>s+", "+v);
        }
    
    0 讨论(0)
  • 2020-11-22 12:23

    Instead of using an enum use a static class.

    replace

    private enum PublishStatuses{
        NotCompleted,
        Completed,
        Error
    };
    

    with

    private static class PublishStatuses{
        public static readonly string NotCompleted = "Not Completed";
        public static readonly string Completed = "Completed";
        public static readonly string Error = "Error";
    };
    

    it will be used like this

    PublishStatuses.NotCompleted; // "Not Completed"
    

    Issue using the top "extension method" solutions:

    A private enum is often used inside another class. The extension method solution is not valid there since it must be in it's own class. This solution can be private and embedded in another class.

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