String representation of an Enum

后端 未结 30 2476
不思量自难忘°
不思量自难忘° 2020-11-22 02:44

I have the following enumeration:

public enum AuthenticationMethod
{
    FORMS = 1,
    WINDOWSAUTHENTICATION = 2,
    SINGLESIGNON = 3
}

T

30条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 03:30

    I use a combination of several of the suggestions above, combined with some caching. Now, I got the idea from some code that I found somewhere on the net, but I can neither remember where I got it or find it. So if anyone ever finds something that looks similar please comment with the attribution.

    Anyway, the usage involves the type converters, so if you are binding to the UI it 'just works'. You can extended with Jakub's pattern for quick code lookup by initializing from the type converter into the static methods.

    The base usage would look like this

    [TypeConverter(typeof(CustomEnumTypeConverter))]
    public enum MyEnum
    {
        // The custom type converter will use the description attribute
        [Description("A custom description")]
        ValueWithCustomDescription,
    
       // This will be exposed exactly.
       Exact
    }
    

    The code for the custom enum type converter follows:

    public class CustomEnumTypeConverter : EnumConverter
        where T : struct
    {
        private static readonly Dictionary s_toString = 
          new Dictionary();
    
        private static readonly Dictionary s_toValue = 
          new Dictionary();
    
        private static bool s_isInitialized;
    
        static CustomEnumTypeConverter()
        {
            System.Diagnostics.Debug.Assert(typeof(T).IsEnum,
              "The custom enum class must be used with an enum type.");
        }
    
        public CustomEnumTypeConverter() : base(typeof(T))
        {
            if (!s_isInitialized)
            {
                Initialize();
                s_isInitialized = true;
            }
        }
    
        protected void Initialize()
        {
            foreach (T item in Enum.GetValues(typeof(T)))
            {
                string description = GetDescription(item);
                s_toString[item] = description;
                s_toValue[description] = item;
            }
        }
    
        private static string GetDescription(T optionValue)
        {
            var optionDescription = optionValue.ToString();
            var optionInfo = typeof(T).GetField(optionDescription);
            if (Attribute.IsDefined(optionInfo, typeof(DescriptionAttribute)))
            {
                var attribute = 
                  (DescriptionAttribute)Attribute.
                     GetCustomAttribute(optionInfo, typeof(DescriptionAttribute));
                return attribute.Description;
            }
            return optionDescription;
        }
    
        public override object ConvertTo(ITypeDescriptorContext context, 
           System.Globalization.CultureInfo culture, 
           object value, Type destinationType)
        {
            var optionValue = (T)value;
    
            if (destinationType == typeof(string) && 
                s_toString.ContainsKey(optionValue))
            {
                return s_toString[optionValue];
            }
    
            return base.ConvertTo(context, culture, value, destinationType);
        }
    
        public override object ConvertFrom(ITypeDescriptorContext context, 
           System.Globalization.CultureInfo culture, object value)
        {
            var stringValue = value as string;
    
            if (!string.IsNullOrEmpty(stringValue) && s_toValue.ContainsKey(stringValue))
            {
                return s_toValue[stringValue];
            }
    
            return base.ConvertFrom(context, culture, value);
        }
    }
    

    }

提交回复
热议问题