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 Description
and 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.
Related Enum values can only be integers
– ramaral