Enum ToString with user friendly strings

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

提交回复
热议问题