2008-09-30 10 views

Respuesta

26
string[] names = Enum.GetNames (typeof(MyEnum)); 

A continuación, sólo poblar el menú desplegable withe la matriz

0

A menudo es útil para definir un mínimo y máximo dentro de su enumeración, que siempre será el primero y últimos artículos. Aquí está un ejemplo muy sencillo utilizando la sintaxis de Delphi:

procedure TForm1.Button1Click(Sender: TObject); 
type 
    TEmployeeTypes = (etMin, etHourly, etSalary, etContractor, etMax); 
var 
    i : TEmployeeTypes; 
begin 
    for i := etMin to etMax do begin 
    //do something 
    end; 
end; 
+0

Excepto que no hay ninguna sintaxis de C# que coincida con eso, por lo que los otros ejemplos son probablemente mejores! Personalmente, no creo que el mínimo/máximo se ajuste a una enumeración, si estuviera definiendo un semáforo, quiero rojo, ámbar, verde, no mínimo, rojo, ámbar, verde, mínimo. –

+0

Erm ... ... Verde, Max. (Vaya) –

5

Se podría iterar a través de la matriz devuelta por el Enum.GetNames method lugar.

public class GetNamesTest { 
enum Colors { Red, Green, Blue, Yellow }; 
enum Styles { Plaid, Striped, Tartan, Corduroy }; 

public static void Main() { 

    Console.WriteLine("The values of the Colors Enum are:"); 
    foreach(string s in Enum.GetNames(typeof(Colors))) 
     Console.WriteLine(s); 

    Console.WriteLine(); 

    Console.WriteLine("The values of the Styles Enum are:"); 
    foreach(string s in Enum.GetNames(typeof(Styles))) 
     Console.WriteLine(s); 
} 
} 
10

utilizar el método de Enum.GetValues:

foreach (TestEnum en in Enum.GetValues(typeof(TestEnum))) 
{ 
    ... 
} 

No es necesario para echarlos en una cadena, y de esa manera sólo se puede recuperar de nuevo echando la propiedad SelectedItem a un TestEnum valor directamente también.

3

Si necesita los valores del combo para corresponder a los valores de la enumeración también se puede usar algo como esto:

foreach (TheEnum value in Enum.GetValues(typeof(TheEnum))) 
    dropDown.Items.Add(new ListItem(
     value.ToString(), ((int)value).ToString() 
    ); 

De esta manera usted puede mostrar los textos en el menú desplegable y obtener de vuelta el value (en propiedad SelectedValue)

24

Sé que otros ya han respondido con una respuesta correcta, sin embargo, si desea utilizar las enumeraciones en un cuadro combinado, es posible que desee ir al patio adicional y asociar cadenas a la enum para que pueda proporcionar más detalles en la cadena mostrada (como espacios entre palabras o cadenas de visualización que utilizan envoltura esn't satisfacer los estándares de codificación)

Esta entrada de blog puede ser útil - Associating Strings with enums in c#

public enum States 
{ 
    California, 
    [Description("New Mexico")] 
    NewMexico, 
    [Description("New York")] 
    NewYork, 
    [Description("South Carolina")] 
    SouthCarolina, 
    Tennessee, 
    Washington 
} 

Como beneficio adicional, también suministra un método de utilidad para enumerar la enumeración que ahora he actualizado con Jon Skeet comenta

public static IEnumerable<T> EnumToList<T>() 
    where T : struct 
{ 
    Type enumType = typeof(T); 

    // Can't use generic type constraints on value types, 
    // so have to do check like this 
    if (enumType.BaseType != typeof(Enum)) 
     throw new ArgumentException("T must be of type System.Enum"); 

    Array enumValArray = Enum.GetValues(enumType); 
    List<T> enumValList = new List<T>(); 

    foreach (T val in enumValArray) 
    { 
     enumValList.Add(val.ToString()); 
    } 

    return enumValList; 
} 

Jon también señaló que en C# 3.0 se puede simplificar a algo como esto (que ahora está volviendo tan ligero que me imagino que sólo podría hacerlo en línea):

public static IEnumerable<T> EnumToList<T>() 
    where T : struct 
{ 
    return Enum.GetValues(typeof(T)).Cast<T>(); 
} 

// Using above method 
statesComboBox.Items = EnumToList<States>(); 

// Inline 
statesComboBox.Items = Enum.GetValues(typeof(States)).Cast<States>(); 
+0

@Ray - Iba a publicar un enlace a la misma publicación en el blog :-) ¡He usado su utilidad muchas veces y funciona como un encanto! –

+1

Algunas mejoras (podría tomar algunos comentarios, me temo): 1) El método podría agregar la restricción "where T: struct" para hacer que la ArgumentException sea menos probable (aunque posible). 2) El foreach puede usar "foreach (T val en enumValArray)" en lugar de formatear y luego volver a analizar. –

+0

Si está usando .NET 3.5, esto se puede hacer con solo: return Enum.GetValues ​​(typeof (T)). Cast (); Eso no molesta en la creación de una lista, ya sea :) –

0

Poco más "complicado" (tal vez exagerado) pero utilizo estos dos métodos para devolver diccionarios para usarlos como fuentes de datos. El primero devuelve el nombre como clave y el segundo valor como clave.

 
public static IDictionary<string, int> ConvertEnumToDictionaryNameFirst<K>() 
{ 
    if (typeof(K).BaseType != typeof(Enum)) 
    { 
    throw new InvalidCastException(); 
    } 

    return Enum.GetValues(typeof(K)).Cast<int>().ToDictionary(currentItem 
    => Enum.GetName(typeof(K), currentItem)); 
} 

O usted podría hacer

 

public static IDictionary<int, string> ConvertEnumToDictionaryValueFirst<K>() 
{ 
    if (typeof(K).BaseType != typeof(Enum)) 
    { 
    throw new InvalidCastException(); 
    } 

    return Enum.GetNames(typeof(K)).Cast<string>().ToDictionary(currentItem 
    => (int)Enum.Parse(typeof(K), currentItem)); 
} 

Esto supone que está utilizando 3.5 embargo. Tendría que reemplazar las expresiones lambda si no.

Uso:

 

    Dictionary list = ConvertEnumToDictionaryValueFirst<SomeEnum>(); 

 
    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
1

El problema de usar las enumeraciones para poblar bajadas de extracción es que cann't tiene caracteres extraños o espacios en las enumeraciones. Tengo un código que extiende enumeraciones para que pueda agregar cualquier carácter que desee.

utilizar de esta manera .. datos

public enum eCarType 
{ 
     [StringValue("Saloon/Sedan")] Saloon = 5, 
     [StringValue("Coupe")] Coupe = 4, 
     [StringValue("Estate/Wagon")] Estate = 6, 
     [StringValue("Hatchback")] Hatchback = 8, 
     [StringValue("Utility")] Ute = 1, 
} 

Bind como tal ..

StringEnum CarTypes = new StringEnum(typeof(eCarTypes)); 
cmbCarTypes.DataSource = CarTypes.GetGenericListValues(); 

Aquí está la clase que amplíe la enumeración.

// Author: Donny V. // blog: http://donnyvblog.blogspot.com

using System; 
    using System.Collections; 
    using System.Collections.Generic; 
    using System.Reflection; 

namespace xEnums 
{ 

    #region Class StringEnum 

    /// <summary> 
    /// Helper class for working with 'extended' enums using <see cref="StringValueAttribute"/> attributes. 
    /// </summary> 
    public class StringEnum 
    { 
     #region Instance implementation 

     private Type _enumType; 
     private static Hashtable _stringValues = new Hashtable(); 

     /// <summary> 
     /// Creates a new <see cref="StringEnum"/> instance. 
     /// </summary> 
     /// <param name="enumType">Enum type.</param> 
     public StringEnum(Type enumType) 
     { 
      if (!enumType.IsEnum) 
       throw new ArgumentException(String.Format("Supplied type must be an Enum. Type was {0}", enumType.ToString())); 

      _enumType = enumType; 
     } 

     /// <summary> 
     /// Gets the string value associated with the given enum value. 
     /// </summary> 
     /// <param name="valueName">Name of the enum value.</param> 
     /// <returns>String Value</returns> 
     public string GetStringValue(string valueName) 
     { 
      Enum enumType; 
      string stringValue = null; 
      try 
      { 
       enumType = (Enum) Enum.Parse(_enumType, valueName); 
       stringValue = GetStringValue(enumType); 
      } 
      catch (Exception) { }//Swallow! 

      return stringValue; 
     } 

     /// <summary> 
     /// Gets the string values associated with the enum. 
     /// </summary> 
     /// <returns>String value array</returns> 
     public Array GetStringValues() 
     { 
      ArrayList values = new ArrayList(); 
      //Look for our string value associated with fields in this enum 
      foreach (FieldInfo fi in _enumType.GetFields()) 
      { 
       //Check for our custom attribute 
       StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[]; 
       if (attrs.Length > 0) 
        values.Add(attrs[0].Value); 

      } 

      return values.ToArray(); 
     } 

     /// <summary> 
     /// Gets the values as a 'bindable' list datasource. 
     /// </summary> 
     /// <returns>IList for data binding</returns> 
     public IList GetListValues() 
     { 
      Type underlyingType = Enum.GetUnderlyingType(_enumType); 
      ArrayList values = new ArrayList(); 
      //List<string> values = new List<string>(); 

      //Look for our string value associated with fields in this enum 
      foreach (FieldInfo fi in _enumType.GetFields()) 
      { 
       //Check for our custom attribute 
       StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[]; 
       if (attrs.Length > 0) 
        values.Add(new DictionaryEntry(Convert.ChangeType(Enum.Parse(_enumType, fi.Name), underlyingType), attrs[0].Value)); 

      } 

      return values; 

     } 

     /// <summary> 
     /// Gets the values as a 'bindable' list<string> datasource. 
     ///This is a newer version of 'GetListValues()' 
     /// </summary> 
     /// <returns>IList<string> for data binding</returns> 
     public IList<string> GetGenericListValues() 
     { 
      Type underlyingType = Enum.GetUnderlyingType(_enumType); 
      List<string> values = new List<string>(); 

      //Look for our string value associated with fields in this enum 
      foreach (FieldInfo fi in _enumType.GetFields()) 
      { 
       //Check for our custom attribute 
       StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[]; 
       if (attrs.Length > 0) 
        values.Add(attrs[0].Value); 
      } 

      return values; 

     } 

     /// <summary> 
     /// Return the existence of the given string value within the enum. 
     /// </summary> 
     /// <param name="stringValue">String value.</param> 
     /// <returns>Existence of the string value</returns> 
     public bool IsStringDefined(string stringValue) 
     { 
      return Parse(_enumType, stringValue) != null; 
     } 

     /// <summary> 
     /// Return the existence of the given string value within the enum. 
     /// </summary> 
     /// <param name="stringValue">String value.</param> 
     /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param> 
     /// <returns>Existence of the string value</returns> 
     public bool IsStringDefined(string stringValue, bool ignoreCase) 
     { 
      return Parse(_enumType, stringValue, ignoreCase) != null; 
     } 

     /// <summary> 
     /// Gets the underlying enum type for this instance. 
     /// </summary> 
     /// <value></value> 
     public Type EnumType 
     { 
      get { return _enumType; } 
     } 

     #endregion 

     #region Static implementation 

     /// <summary> 
     /// Gets a string value for a particular enum value. 
     /// </summary> 
     /// <param name="value">Value.</param> 
     /// <returns>String Value associated via a <see cref="StringValueAttribute"/> attribute, or null if not found.</returns> 
     public static string GetStringValue(Enum value) 
     { 
      string output = null; 
      Type type = value.GetType(); 

      if (_stringValues.ContainsKey(value)) 
       output = (_stringValues[value] as StringValueAttribute).Value; 
      else 
      { 
       //Look for our 'StringValueAttribute' in the field's custom attributes 
       FieldInfo fi = type.GetField(value.ToString()); 
       StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[]; 
       if (attrs.Length > 0) 
       { 
        _stringValues.Add(value, attrs[0]); 
        output = attrs[0].Value; 
       } 

      } 
      return output; 

     } 

     /// <summary> 
     /// Parses the supplied enum and string value to find an associated enum value (case sensitive). 
     /// </summary> 
     /// <param name="type">Type.</param> 
     /// <param name="stringValue">String value.</param> 
     /// <returns>Enum value associated with the string value, or null if not found.</returns> 
     public static object Parse(Type type, string stringValue) 
     { 
      return Parse(type, stringValue, false); 
     } 

     /// <summary> 
     /// Parses the supplied enum and string value to find an associated enum value. 
     /// </summary> 
     /// <param name="type">Type.</param> 
     /// <param name="stringValue">String value.</param> 
     /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param> 
     /// <returns>Enum value associated with the string value, or null if not found.</returns> 
     public static object Parse(Type type, string stringValue, bool ignoreCase) 
     { 
      object output = null; 
      string enumStringValue = null; 

      if (!type.IsEnum) 
       throw new ArgumentException(String.Format("Supplied type must be an Enum. Type was {0}", type.ToString())); 

      //Look for our string value associated with fields in this enum 
      foreach (FieldInfo fi in type.GetFields()) 
      { 
       //Check for our custom attribute 
       StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[]; 
       if (attrs.Length > 0) 
        enumStringValue = attrs[0].Value; 

       //Check for equality then select actual enum value. 
       if (string.Compare(enumStringValue, stringValue, ignoreCase) == 0) 
       { 
        output = Enum.Parse(type, fi.Name); 
        break; 
       } 
      } 

      return output; 
     } 

     /// <summary> 
     /// Return the existence of the given string value within the enum. 
     /// </summary> 
     /// <param name="stringValue">String value.</param> 
     /// <param name="enumType">Type of enum</param> 
     /// <returns>Existence of the string value</returns> 
     public static bool IsStringDefined(Type enumType, string stringValue) 
     { 
      return Parse(enumType, stringValue) != null; 
     } 

     /// <summary> 
     /// Return the existence of the given string value within the enum. 
     /// </summary> 
     /// <param name="stringValue">String value.</param> 
     /// <param name="enumType">Type of enum</param> 
     /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param> 
     /// <returns>Existence of the string value</returns> 
     public static bool IsStringDefined(Type enumType, string stringValue, bool ignoreCase) 
     { 
      return Parse(enumType, stringValue, ignoreCase) != null; 
     } 

     #endregion 
    } 

    #endregion 

    #region Class StringValueAttribute 

    /// <summary> 
    /// Simple attribute class for storing String Values 
    /// </summary> 
    public class StringValueAttribute : Attribute 
    { 
     private string _value; 

     /// <summary> 
     /// Creates a new <see cref="StringValueAttribute"/> instance. 
     /// </summary> 
     /// <param name="value">Value.</param> 
     public StringValueAttribute(string value) 
     { 
      _value = value; 
     } 

     /// <summary> 
     /// Gets the value. 
     /// </summary> 
     /// <value></value> 
     public string Value 
     { 
      get { return _value; } 
     } 
    } 

    #endregion 
} 

1

.NET 3.5 hace que sea sencillo mediante el uso de métodos de extensión:

enum Color {Red, Green, Blue} 

se pueden repetir con

Enum.GetValues(typeof(Color)).Cast<Color>() 

o definir un nuevo método genérico estática:

static IEnumerable<T> GetValues<T>() { 
    return Enum.GetValues(typeof(T)).Cast<T>(); 
} 

Tenga en cuenta que la iteración con el método Enum.GetValues ​​() usa la reflexión y, por lo tanto, tiene penalizaciones de rendimiento.

Cuestiones relacionadas