How to recover the description of an enumerator?

Asked

Viewed 1,831 times

5

I have the following enumerator

public enum MeuEnumerador
{
    [Description("Descrição do item do enumerador")]
    Enumerador1 = 1,
    [Description("Outra descrição")]
    Enumerador2 = 2
}

How do I get the value that is in Descriptionof the enumerator?

2 answers

4


I found a solution by creating the following extensions for the type Enum

public static T ObterAtributoDoTipo<T>(this Enum valorEnum) where T : System.Attribute
{
    var type = valorEnum.GetType();
    var memInfo = type.GetMember(valorEnum.ToString());
    var attributes = memInfo[0].GetCustomAttributes(typeof(T), false);
    return (attributes.Length > 0) ? (T)attributes[0] : null;
}

public static string ObterDescricao(this Enum valorEnum)
{
    return valorEnum.ObterAtributoDoTipo<DescriptionAttribute>().Description;
}

Where the extension ObterAtributoDoTipo<T> will return to me the attribute that is requested, in this case the Description. Example of use:

var meuEnumerador = MeuEnumerador.Enumerador1;
Attribute atributo = meuEnumerador.ObterAtributoDoTipo<DescriptionAttribute>();

And the extent ObterDescrição will indeed return me to Descriptionand for that she uses the other extension to fetch the attribute. Example of use:

var meuEnumerador = MeuEnumerador.Enumerador1;
string descricao = meuEnumerador.ObterDescricao();

I looked in several places about how to do it, and this was the best solution I could find, in case anyone knows other ways to do it, share in the answers.

0

just use getDescription:

var teste = MeuEnumerador.GetDescription();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.