Get a List of my enum attributes with a generic method

前端 未结 3 847
面向向阳花
面向向阳花 2020-12-10 07:10

At start, we have this basic enum.

public enum E_Levels {

    [ValueOfEnum(\"Low level\")]
    LOW,

    [ValueOfEnum(\"Normal level\")]
    NORMAL,

    [V         


        
3条回答
  •  执笔经年
    2020-12-10 08:04

    .Net already has the same attribute Description so you can use this one instead ValueOfEnum.

    What about dynamic and extension on type and following example

    [TestFixture]
    public sealed class ForTest
    {
        [Test]
        public void Test()
        {
            var values = typeof(Levels).ToValues();
            values.ForEach(Console.WriteLine);
        }
    }
    
    public static class TypeExtensions
    {
        public static List ToValues(this Type value)
        {
            var result = new List();
            var values = ToConcreteValues(value);
            foreach (dynamic item in values)
            {
                Description attribute = GetAttribute(item);
                result.Add(attribute.Description);
            }
            return result;
        }
    
        private static dynamic ToConcreteValues(Type enumType)
        {
            Array values = Enum.GetValues(enumType);
            Type list = typeof (List<>);
            Type resultType = list.MakeGenericType(enumType);
            dynamic result = Activator.CreateInstance(resultType);
            foreach (object value in values)
            {
                dynamic concreteValue = Enum.Parse(enumType, value.ToString());
                result.Add(concreteValue);
            }
            return result;
        }
    
        private static TAttribute GetAttribute(dynamic value)
            where TAttribute : Attribute
        {
            Type type = value.GetType();
            FieldInfo fieldInfo = type.GetField(Enum.GetName(type, value));
            return (TAttribute) Attribute.GetCustomAttribute(fieldInfo, typeof (TAttribute));
        }
    }
    
    public enum Levels
    {
        [Description("Low level")]LOW,
        [Description("Normal level")] NORMAL,
        [Description("High level")] HIGH
    }
    

    result output:

    Low level
    Normal level
    High level
    

提交回复
热议问题