2011-05-17 13 views
5

Tengo una clase de auditoría que recupera todo por reflexión. Necesito en mi punto actual saber si una propiedad específica es un Enum, pero estoy obteniendo un comportamiento extraño:Mi Enum no se reconoce utilizando reflection y PropertyInfo

Durante la iteración de foreach q.PropertyType.IsEnum return false. Y usando Quick Watcher, la propiedad es realmente falsa, y también IsClass. Así que esto es básicamente nada :)

Estudiando un poco más sobre el problema encontré que Nullable Enum devuelve falso en IsEnum. ¿Cómo puedo ignorar este nulo y verificar si la propiedad es una enumeración o no?

+5

Nit: Los números del 30 al 39 se deletrean "Treinta", no "Tercero". –

+0

@JSBangs, concéntrate, por favor. : D – Custodio

+0

@ Custódio ¿Qué es 'ReflectionUtil'? –

Respuesta

5

IsEnum devolverá false cuando su propiedad sea de tipo anulable. En este caso, llamando al Nullable.GetUnderlyingType en q.PropertyType devolverá el tipo que desee. Entonces puedes consultar con IsEnum.

2

Editar: He probado su enumeración, y es fetchable. Una llamada a Foo.GetEnumProperties devuelve una matriz con "TestProp" en ella:

public enum MyEnum 
    { 
     [XmlEnumAttribute("Twenty and Something")] 
     TwentyTree = 1, 
     [XmlEnumAttribute("Thirty and Something")] 
     Thirdyfour 
    } 

    class Foo 
    { 
     public MyEnum TestProp { get; set; } 


     /// <summary> 
     /// Get a list of properties that are enum types 
     /// </summary> 
     /// <returns>Enum property names</returns> 
     public static string[] GetEnumProperties() 
     { 
      MemberInfo[] members = typeof(Foo).FindMembers(MemberTypes.Property, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, null, null); 
      List<string> retList = new List<string>(); 
      foreach (MemberInfo nextMember in members) 
      { 
       PropertyInfo nextProp = nextMember as PropertyInfo; 
       if (nextProp.PropertyType.IsEnum) 
        retList.Add(nextProp.Name); 
      } return retList.ToArray(); 
     } 
    } 

para hacer lo que está tratando de hacer, yo uso System.ComponentModel.DescriptionAttribute, a continuación, se puede recuperar de esta manera:

/// <summary> 
/// Get the description for the enum 
/// </summary> 
/// <param name="value">Value to check</param> 
/// <returns>The description</returns> 
public static string GetDescription(object value) 
{ 
    Type type = value.GetType(); 
    string name = Enum.GetName(type, value); 
    if (name != null) 
    { 
     FieldInfo field = type.GetField(name); 
     if (field != null) 
     { 
      DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; 
      if (attr != null) 
      { 
       string desc = attr.Description; 
       return desc; 
      } 
     } 
    } 
    return value.ToString(); 
} 
+0

La pregunta tiene como objetivo descubrir qué está mal con la declaración MyEnum. – Custodio

+1

No hay nada de malo con su declaración enum. Simplemente estás obteniendo el atributo de una manera que no funcionará. –

+0

Agradable. Entonces, para adaptarme a mi pregunta, ¿cuál es la mejor manera de devolver un valor bool que diga si una propiedad es Enum o no – Custodio

Cuestiones relacionadas