Posible duplicado:
Encontrar un valor enum por su atributo de descripción
Tengo un método de extensión genérico que obtiene el atributo Description
de un Enum
:
enum Animal { [Description("")] NotSet = 0, [Description("Giant Panda")] GiantPanda = 1, [Description("Lesser Spotted Anteater")] LesserSpottedAnteater = 2 } public static string GetDescription(this Enum value) { FieldInfo field = value.GetType().GetField(value.ToString()); DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; return attribute == null ? value.ToString() : attribute.Description; }
entonces yo puedo hacer …
string myAnimal = Animal.GiantPanda.GetDescription(); // = "Giant Panda"
ahora, estoy tratando de encontrar la función equivalente en la otra dirección, algo así como …
Animal a = (Animal)Enum.GetValueFromDescription("Giant Panda", typeof(Animal));
public static class EnumEx { public static T GetValueFromDescription(string description) { var type = typeof(T); if(!type.IsEnum) throw new InvalidOperationException(); foreach(var field in type.GetFields()) { var attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; if(attribute != null) { if(attribute.Description == description) return (T)field.GetValue(null); } else { if(field.Name == description) return (T)field.GetValue(null); } } throw new ArgumentException("Not found.", "description"); // or return default(T); } }
Uso:
var panda = EnumEx.GetValueFromDescription("Giant Panda");
en lugar de métodos de extensión, solo prueba un par de métodos estáticos
public static class Utility { public static string GetDescriptionFromEnumValue(Enum value) { DescriptionAttribute attribute = value.GetType() .GetField(value.ToString()) .GetCustomAttributes(typeof (DescriptionAttribute), false) .SingleOrDefault() as DescriptionAttribute; return attribute == null ? value.ToString() : attribute.Description; } public static T GetEnumValueFromDescription(string description) { var type = typeof(T); if (!type.IsEnum) throw new ArgumentException(); FieldInfo[] fields = type.GetFields(); var field = fields .SelectMany(f => f.GetCustomAttributes( typeof(DescriptionAttribute), false), ( f, a) => new { Field = f, Att = a }) .Where(a => ((DescriptionAttribute)a.Att) .Description == description).SingleOrDefault(); return field == null ? default(T) : (T)field.Field.GetRawConstantValue(); } }
y usar aquí
var result1 = Utility.GetDescriptionFromEnumValue( Animal.GiantPanda); var result2 = Utility.GetEnumValueFromDescription( "Lesser Spotted Anteater");
La solución funciona bien, excepto si tiene un servicio web.
Debería hacer lo Siguiente ya que el Atributo de Descripción no es serializable.
[DataContract] public enum ControlSelectionType { [EnumMember(Value = "Not Applicable")] NotApplicable = 1, [EnumMember(Value = "Single Select Radio Buttons")] SingleSelectRadioButtons = 2, [EnumMember(Value = "Completely Different Display Text")] SingleSelectDropDownList = 3, } public static string GetDescriptionFromEnumValue(Enum value) { EnumMemberAttribute attribute = value.GetType() .GetField(value.ToString()) .GetCustomAttributes(typeof(EnumMemberAttribute), false) .SingleOrDefault() as EnumMemberAttribute; return attribute == null ? value.ToString() : attribute.Value; }
Debe ser bastante sencillo, es exactamente lo contrario de su método anterior;
public static int GetEnumFromDescription(string description, Type enumType) { foreach (var field in enumType.GetFields()) { DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))as DescriptionAttribute; if(attribute == null) continue; if(attribute.Description == description) { return (int) field.GetValue(null); } } return 0; }
Uso:
Console.WriteLine((Animal)GetEnumFromDescription("Giant Panda",typeof(Animal)));
No puede extender Enum
ya que es una clase estática. Solo puede extender instancias de un tipo. Con esto en mente, vas a tener que crear un método estático para hacer esto; lo siguiente debería funcionar cuando se combina con su método existente GetDescription
:
public static class EnumHelper { public static T GetEnumFromString(string value) { if (Enum.IsDefined(typeof(T), value)) { return (T)Enum.Parse(typeof(T), value, true); } else { string[] enumNames = Enum.GetNames(typeof(T)); foreach (string enumName in enumNames) { object e = Enum.Parse(typeof(T), enumName); if (value == GetDescription((Enum)e)) { return (T)e; } } } throw new ArgumentException("The value '" + value + "' does not match a valid enum name or description."); } }
Y el uso de esto sería algo como esto:
Animal giantPanda = EnumHelper.GetEnumFromString("Giant Panda");
Necesita repetir todos los valores enum en Animal y devolver el valor que coincida con la descripción que necesita.