2008-09-30 4 views

Répondre

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

Ensuite, il suffit remplir le menu déroulant withe le tableau

0

Il est souvent utile de définir un Min et Max dans votre ENUM, qui sera toujours la première et derniers articles Voici un exemple très simple en utilisant la syntaxe 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

Sauf qu'il n'y a pas de syntaxe C# correspondante, donc les autres exemples sont probablement meilleurs! Personnellement, je ne pense pas min/max convenir à une énumération, si je définissais un feu de circulation, je veux Rouge, Ambre, Vert pas Min, Rouge, Ambre, Vert, Min. –

+0

Erm ... ... Vert, Max. (oops) –

5

Vous pouvez parcourir le tableau retourné par la Enum.GetNames method à la place.

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

Utilisez la méthode Enum.GetValues:

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

Vous n'avez pas besoin de les jeter à une chaîne, et de cette façon vous pouvez simplement les récupérer en arrière en jetant la propriété SelectedItem à un TestEnum valeur directement aussi bien.

3

Si vous avez besoin des valeurs du combo pour correspondre aux valeurs du ENUM vous pouvez également utiliser quelque chose comme ceci:

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

De cette façon, vous pouvez afficher les textes dans le menu déroulant et obtenir à la value (dans la propriété SelectedValue)

24

Je sais que d'autres personnes ont déjà répondu avec une réponse correcte. Toutefois, si vous souhaitez utiliser les énumérations dans une zone de liste déroulante, vous pouvez utiliser la barre supplémentaire et associer des chaînes à enum afin que vous puissiez fournir plus de détails dans la chaîne affichée (comme les espaces entre les mots ou les chaînes d'affichage en utilisant le boîtier qui fait esn't correspondent à vos normes de codage)

Cette entrée de blog peut être utile - Associating Strings with enums in c#

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

En prime, il a également fourni une méthode utilitaire pour énumérer l'énumération que je suis maintenant mis à jour avec Jon Skeet de commentaires

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 a également souligné que, dans C# 3.0, il peut être simplifié à quelque chose comme ça (qui est maintenant devient si léger que je vous pouviez faire imaginer en ligne):

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 - J'allais poster un lien vers le même blog :-) J'ai utilisé son utilitaire plusieurs fois et ça fonctionne comme un charme! –

+1

Quelques améliorations (peut-être quelques commentaires, j'en ai peur): 1) La méthode pourrait ajouter la contrainte "where T: struct" pour rendre l'exception ArgumentException moins probable (bien que toujours possible). 2) Foreach peut utiliser "foreach (T val in enumValArray)" au lieu de le formater puis de le reparer. –

+0

Si vous utilisez .NET 3.5, ceci peut être fait avec juste: return Enum.GetValues ​​(typeof (T)). Cast (); –

0

Un peu plus "compliqué" (peut-être exagéré) mais j'utilise ces deux méthodes pour retourner les dictionnaires à utiliser comme sources de données. Le premier renvoie le nom en tant que clé et la seconde valeur en tant que clé.

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

Ou vous pourriez faire

 

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

Cela suppose que vous utilisez 3.5 cependant. Vous devrez remplacer les expressions lambda sinon.

Utilisation:

 

    Dictionary list = ConvertEnumToDictionaryValueFirst<SomeEnum>(); 

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

Le problème avec l'utilisation énumérations pour remplir démoraliser est que vous avez cann't des personnages ou des espaces étranges dans énumérations. J'ai un code qui étend les énumérations de sorte que vous pouvez ajouter n'importe quel caractère que vous voulez.

Utilisez comme ça ..

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, 
} 

données Bind comme si ..

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

Voici la classe qui étend la ENUM.

// 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

3,5 .NET fait simple à l'aide des méthodes d'extension:

enum Color {Red, Green, Blue} 

peut itérer avec

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

ou définir une nouvelle méthode générique statique:

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

Gardez à l'esprit que l'itération avec la méthode Enum.GetValues ​​() utilise la réflexion et donc des pénalités de performance.

Questions connexes