vendredi 17 septembre 2021

How to efficiently get value and attribute for each value in an enum?

I want to get the value and an attribute for each value in an enum.

I know I can loop the values.

foreach (TEnum value in Enum.GetValues(typeof(TEnum)))
{
    MemberInfo? info = value.GetType().GetMember(value.ToString()).FirstOrDefault();
    if (info != null)
    {
        CustomAttribute? attribute = info.GetCustomAttribute<CustomAttribute>();
        if (attribute != null)
            EnumLookup.Add(attribute.Code, value)
    }
}

But this seems horribly inefficient, having to call GetMember() and GetCustomAttribute() for each and every value.

If I used GetMembers() or GetFields() to get information for all the enum value, and then looped through them, it seems that would be more efficient.

FieldInfo[]? fields = typeof(TEnum).GetFields(BindingFlags.Public | BindingFlags.Static);
foreach (FieldInfo field in fields)
{
    CustomAttribute? attribute = field.GetCustomAttribute<CustomAttribute>();
    if (attribute != null)
        EnumLookup.Add(code, /* Whoops! What to put here? */ );
}

But then how could I get the value for each one?

Enums are strange because the values are like static fields, but there appears to be no way to get the value of a static field through reflection.

Note: EnumLookup is a dictionary that maps a code (stored in CustomAttribute) to the enum value.





Aucun commentaire:

Enregistrer un commentaire