C# 是否有一种方法可以迭代并反映枚举中包含的成员名称和值?

C# 是否有一种方法可以迭代并反映枚举中包含的成员名称和值?,c#,reflection,enums,iteration,enumeration,C#,Reflection,Enums,Iteration,Enumeration,假设我有以下enum: public enum Colors { White = 10, Black = 20, Red = 30, Blue = 40 } 我想知道是否有一种方法可以遍历Colors的所有成员,以查找成员名称及其值。您可以使用和: var name=Enum.GetNames(typeof(Colors)); var values=Enum.GetValues(typeof(Colors)); 对于(inti=0;i你可以这样做 for (

假设我有以下
enum

public enum Colors
{
    White = 10,
    Black = 20,
    Red = 30,
    Blue = 40
}
我想知道是否有一种方法可以遍历
Colors
的所有成员,以查找成员名称及其值。

您可以使用和:

var name=Enum.GetNames(typeof(Colors));
var values=Enum.GetValues(typeof(Colors));

对于(inti=0;i你可以这样做

  for (int i = 0; i < typeof(DepartmentEnum).GetFields().Length - 1; i++)
            {
                DepartmentEnum de = EnumExtensions.NumberToEnum<DepartmentEnum>(i);
                pairs.Add(new KeyValuePair<string, string>(de.ToDescription(), de.ToString()));
            }
for(inti=0;i
以下是扩展本身:

  public static class EnumExtensions
    {
        public static string ToDescription(this Enum en) 
        {
            Type type = en.GetType();

            MemberInfo[] memInfo = type.GetMember(en.ToString());

            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),false);

                if (attrs != null && attrs.Length > 0)

                    return ((DescriptionAttribute)attrs[0]).Description;
            }

            return en.ToString();
        }

        public static TEnum NumberToEnum<TEnum>(int number )
        {
            return (TEnum)Enum.ToObject(typeof(TEnum), number);
        }
    }
公共静态类枚举扩展
{
公共静态字符串ToDescription(此枚举为en)
{
Type Type=en.GetType();
MemberInfo[]memInfo=type.GetMember(en.ToString());
if(memInfo!=null&&memInfo.Length>0)
{
对象[]attrs=memInfo[0]。GetCustomAttributes(typeof(DescriptionAttribute),false);
如果(属性!=null&&attrs.Length>0)
返回((DescriptionAttribute)属性[0])。说明;
}
返回en.ToString();
}
公共静态十位数枚举(整数)
{
return(TEnum)Enum.ToObject(typeof(TEnum),number);
}
}

哇,谈谈类似的例子。+1。@Ryan:是的-没有太大不同;)回答得很好,但我很好奇:为什么
++I
?@Ben:而不是I++?这是我在C/C++时代的一个习惯,在那里它很重要。。。(我仍然编写大量代码,所以我喜欢保持这个习惯)@Reed ahh,谢谢你的解释。是的,我对
I++
很好奇。虽然我知道它在C#中是允许的,但我从未见过有人使用它,也不确定是否有区别。
  public static class EnumExtensions
    {
        public static string ToDescription(this Enum en) 
        {
            Type type = en.GetType();

            MemberInfo[] memInfo = type.GetMember(en.ToString());

            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),false);

                if (attrs != null && attrs.Length > 0)

                    return ((DescriptionAttribute)attrs[0]).Description;
            }

            return en.ToString();
        }

        public static TEnum NumberToEnum<TEnum>(int number )
        {
            return (TEnum)Enum.ToObject(typeof(TEnum), number);
        }
    }