Get a List of my enum attributes with a generic method

前端 未结 3 850
面向向阳花
面向向阳花 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:52

    You might try casting (Enum)(object)l, changing ToValueOfEnum to take an object, or just inline the method:

    public static List GetValuesOf()
    {
    
        List levelsToReturn = new List();
        var levels = Enum.GetValues(typeof(T)).Cast();
        foreach (T value in levels)
        {
            FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
            ValueOfEnum[] attribs = fieldInfo.GetCustomAttributes(typeof(ValueOfEnum), false) as ValueOfEnum[];
            levelsToReturn.Add(attribs.Length > 0 ? attribs[0].value : null);
        }
    
        return levelsToReturn;
    }
    

    Here's a one-line solution using the casting approach:

    return new List(Enum.GetValues(typeof(T)).Cast().Select(x => x.ToValueOfEnum()));
    

    In case you weren't clear on why T wasn't recognized as an Enum like E_Levels is, that's because you didn't specify that T : enum. Unfortunately, you can't specify that in C# (even though the CLR supports it), so other approaches like runtime checking/assuming (such as what I'm suggesting here) or post-compile code modifications (e.g. unconstrained-melody) have to be done.

提交回复
热议问题