2010-02-05 9 views

Respuesta

12

Puede utilizar Enum.GetNames y Enum.GetValues:

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

for (int i=0;i<names.Length;++i) 
{ 
    Console.WriteLine("{0} : {1}", names[i], (int)values.GetValue(i)); 
} 

Nota: Cuando traté de ejecutar el código usando values[i], se inició una excepción porque values es de tipo Array.

+0

Wow, hablar de ejemplos similares. +1. –

+0

@Ryan: Sí, no muy diferente;) –

+0

Excelente respuesta, pero tengo curiosidad: ¿por qué '++ i'? –

1

Se podría hacer algo como esto

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

Aquí está la extensión misma:

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); 
     } 
    } 
Cuestiones relacionadas