mercredi 1 mai 2019

Get type member's MemberInfo without iteration of all type members

I have written some version of the following method in a dozen different solutions:

//Get the string specified in the "Description" attribute of an enum value
public static string GetDescription<T>(this T enumVal) where T : Enum
{
    var type = enumVal.GetType();
    var member = type.GetMember(enumVal.ToString()).First();
    var attrib = member.GetCustomAttribute<DescriptionAttribute>();
    return attrib?.Description ?? null;
}

Given this enum:

public enum MyEnum
{
    [Description("The First")]  TheFirst,
    [Description("The Second")] TheSecond
}

I am then able to write the following code:

MyEnum.TheFirst.GetDescription()
>> "The First"

This method works and it's the only way I've seen people do it. Here's my question:

How can I get the MemberInfo without using Type.GetMember() to iterate the type members to match a string? If the input (MyEnum.TheFirst) is already a strongly qualified member, why does reflection require me to abandon that and essentially search for the member as a string?

The code I want to write is:

public static string GetDescription<T>(this T enumVal) where T : Enum
{
    var member = enumVal.GetMember(); //gets the fully qualified MemberInfo object
    var attrib = member.GetCustomAttribute<DescriptionAttribute>();
    return attrib?.Description ?? null;
}

I'm aware that I could write an extension method to do this, but it wouldn't solve the fundamental issue: that I have to use a string search (again, via the System.Reflection.GetMember(string name) method) just to get information that should already be readily available.

Please let me know if I'm thinking about this the wrong way, or if there's another, simpler approach to this.





Aucun commentaire:

Enregistrer un commentaire