My Enum is not recognized by reflection and PropertyInfo

I have an audit class that restores everything by reflection. I need to find out if a particular property is really Enum, but I get weird behavior:

During iteration, foreach q.PropertyType.IsEnumreturns false. And using Quick watcher the property is really false, and IsClass too. So it's basically nothing :)

Studying a bit more about the problem, I found that the Nullable Enum returns false in IsEnum. How can I ignore this nullable value and check if the property is an enumeration or not?

+5
source share
3 answers

IsEnum false, . Nullable.GetUnderlyingType q.PropertyType . IsEnum.

+5

: , . Foo.GetEnumProperties "TestProp" :

    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();
        }
    }

, , System.ComponentModel.DescriptionAttribute, :

/// <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();
}
+2

Enums , Nullable, IsEnum .
@Skeet , #. .

0

All Articles