At start, we have this basic enum.
public enum E_Levels {
[ValueOfEnum(\"Low level\")]
LOW,
[ValueOfEnum(\"Normal level\")]
NORMAL,
[V
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.