Get a List of my enum attributes with a generic method

前端 未结 3 858
面向向阳花
面向向阳花 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 07:59

    Let's try to keep this more general purpose.

    I have an extension method that could grab attributes off of enum values. This would give you quick access to the attributes.

    public static class EnumExtensions
    {
        public static TAttribute GetAttribute(this Enum value)
            where TAttribute : Attribute
        {
            var type = value.GetType();
            var name = Enum.GetName(type, value);
            return type.GetField(name)
                .GetCustomAttributes(false)
                .OfType()
                .SingleOrDefault();
        }
    }
    

    Using this, you could create some queries to get what you want.

    var valuesOfLevels =
        Enum.GetValues(typeof(E_Levels)).Cast()
            .Select(level => level.GetAttribute().Value);
    

    So your GetValuesOf() method (which is not a great name for such a specialty method IMHO) can be written like this:

    public static List GetValuesOf()
        where TEnum : struct // can't constrain to enums so closest thing
    {
        return Enum.GetValues(typeof(TEnum)).Cast()
                   .Select(val => val.GetAttribute().Value)
                   .ToList();
    }
    

    Now you may call the method like so:

    var levelValues = GetValueOf();
    // levelValues = { "Low level", "Normal level", "High level" }
    

提交回复
热议问题