简体   繁体   中英

How to get the list of Enum properties of a class?

Closely related to How to get the list of properties of a class? , I've gotten as far as that question goes but I'm interested in knowing which of the returned properties are enumerations. My first (unlikely) guess was along the lines of:

foo A;

foreach (var property in A.GetType().GetProperties())
{
    if (property.PropertyType is Enum)
        //Celebrate
}

This did not work. It's valid, but Visual Studio was even able to warn in advance that "The given expression is never of the provided ('System.Enum') type".

To my understanding, C# Enums are wrappers over top of primitive counting types (defaulting with int, but also possibly byte, short, etc). I can easily test to see of the properties are of these types, but that will lead me to a lot of false positives in my search for Enums.

You are almost there. Just use

if (property.PropertyType.IsEnum)
    // Celebrate

In .NET 4.5, you might need to get a TypeInfo object from the property type.

property is a PropertyInfo object.
PropertyInfo doesn't inherit Enum , so that can never be true.

You want to check the PropertyType – the Type object describing the property's return type.

if (property.PropertyType is Enum) won't work either, for the same reason – Type doesn't inherit Enum .

Instead, you need to look at the properties of the Type object to see whether it's an enum type.
In this case, you can just use its IsEnum property; in the more general case, you would want to call IsSubclassOf() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM