简体   繁体   English

.net通过反射获取枚举类型

[英].Net getting enum type through reflection

I'm having an structure with a bunch of properties, all enums. 我有一个带有一堆属性的结构,所有枚举。

What I like to do is iterate through the properties and get the underlying type of the enum, or the enums list of values. 我想做的是遍历属性并获取枚举的基础类型或值的枚举列表。 So I can create dropdownlists for them without writing code for each of them. 因此,我可以为他们创建下拉列表,而无需为他们每个人编写代码。

I managed to get the selected value, name of enum, description etc. But I'm stuck on this part. 我设法获得了所选的值,枚举的名称,描述等。但是我被困在这一部分。 Any help would be greatly appreciated. 任何帮助将不胜感激。

You can easily iterate through each property of a class using reflection and determine which of them are enums and which are not (by using IsEnum property of the PropertyType class). 您可以使用反射轻松地遍历类的每个属性,并确定其中哪些是枚举,哪些不是(通过使用PropertyType类的IsEnum属性)。 For each enum that you have found you can then check its underlying type. 然后,对于找到的每个枚举,都可以检查其基础类型。

The you could use such a generic extension method: 您可以使用这样的通用扩展方法:

   public static IDictionary<string, string> EnumToDictionary(this Type t)
    {
        if (t == null) throw new NullReferenceException();
        if (!t.IsEnum) throw new InvalidCastException("object is not an Enumeration");

        string[] names = Enum.GetNames(t);
        Array values = Enum.GetValues(t);

        return (from i in Enumerable.Range(0, names.Length)
                select new { Key = names[i], Value = (int)values.GetValue(i) })
                    .ToDictionary(k => k.Key, k => k.Value.ToString());
    }

And then call it like this for each enum type that you have found in your class: 然后针对您在课程中发现的每种枚举类型,像这样调用它:

var result = typeOfEnum.EnumToDictionary();

Where typeOfEnum is the underlying type of an enum that you have found while iterating through the properties of a class. 其中,typeOfEnum是在遍历类的属性时发现的枚举的基础类型。

You can then use the result to populate appropriate dropdownlists with enum's names and values. 然后,您可以使用结果用枚举的名称和值填充适当的下拉列表。

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

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