简体   繁体   English

如何获取一个类的Enum属性列表?

[英]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". 这是有效的,但是Visual Studio甚至可以提前警告“给定的表达式永远不会是所提供的('System.Enum')类型的”。

To my understanding, C# Enums are wrappers over top of primitive counting types (defaulting with int, but also possibly byte, short, etc). 据我了解,C#枚举是原始计数类型之上的包装器(默认为int,但也可能为byte,short等)。 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. 我可以轻松地测试一下这些类型的属性,但这会导致我在搜索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. 在.NET 4.5中,您可能需要从属性类型获取TypeInfo对象。

property is a PropertyInfo object. property是一个PropertyInfo对象。
PropertyInfo doesn't inherit Enum , so that can never be true. PropertyInfo不继承Enum ,所以永远不可能是true。

You want to check the PropertyType – the Type object describing the property's return type. 您要检查PropertyType –描述属性返回类型的Type对象。

if (property.PropertyType is Enum) won't work either, for the same reason – Type doesn't inherit Enum . if (property.PropertyType is Enum)也不起作用,出于相同的原因– Type不继承Enum

Instead, you need to look at the properties of the Type object to see whether it's an enum type. 相反,您需要查看Type对象的属性以查看其是否为枚举类型。
In this case, you can just use its IsEnum property; 在这种情况下,您可以只使用其IsEnum属性。 in the more general case, you would want to call IsSubclassOf() . 在更一般的情况下,您需要调用IsSubclassOf()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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