有没有办法迭代所有枚举值?

可能重复:
C#:如何枚举枚举?

主题说全部。 我想用它来在combobox中添加枚举的值。

谢谢

vIceBerg

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

然后只需填充数组的下拉列表

我知道其他人已经回答了正确的答案,但是,如果你想在combobox中使用枚举,你可能想要额外的院子并将字符串关联到枚举,这样你就可以提供更多细节。显示的字符串(例如使用与您的编码标准不匹配的字词或显示字符串之间的空格)

此博客条目可能很有用 – 将字符串与c#中的枚举相关联

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

作为奖励,他还提供了一种实用程序方法,用于枚举我现在使用Jon Skeet的评论更新的枚举

 public static IEnumerable EnumToList() 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 enumValList = new List(); foreach (T val in enumValArray) { enumValList.Add(val.ToString()); } return enumValList; } 

乔恩还指出,在C#3.0中,它可以简化为类似的东西(现在它变得如此轻盈,我想你可以在线进行):

 public static IEnumerable EnumToList() where T : struct { return Enum.GetValues(typeof(T)).Cast(); } // Using above method statesComboBox.Items = EnumToList(); // Inline statesComboBox.Items = Enum.GetValues(typeof(States)).Cast(); 

使用Enum.GetValues方法:

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

您不需要将它们转换为字符串,这样您就可以通过直接将SelectedItem属性转换为TestEnum值来检索它们。

您可以遍历Enum.GetNames方法返回的数组。

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

如果您需要组合的值与枚举的值相对应,您还可以使用以下内容:

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

通过这种方式,您可以在下拉列表中显示文本并获取值(在SelectedValue属性中)

.NET 3.5通过使用扩展方法使其变得简单:

 enum Color {Red, Green, Blue} 

可以迭代

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

或定义一个新的静态generics方法:

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

请记住,使用Enum.GetValues()方法进行迭代会使用reflection,因此会产生性能损失。

使用枚举来填充下拉的问题是你不能在枚举中有奇怪的字符或空格。 我有一些扩展枚举的代码,以便您可以添加任何想要的字符。

像这样用它..

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

像这样绑定数据..

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

这是扩展枚举的类。

 // 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 ///  /// Helper class for working with 'extended' enums using  attributes. ///  public class StringEnum { #region Instance implementation private Type _enumType; private static Hashtable _stringValues = new Hashtable(); ///  /// Creates a new  instance. ///  /// Enum type. 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; } ///  /// Gets the string value associated with the given enum value. ///  /// Name of the enum value. /// String Value 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; } ///  /// Gets the string values associated with the enum. ///  /// String value array 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(); } ///  /// Gets the values as a 'bindable' list datasource. ///  /// IList for data binding public IList GetListValues() { Type underlyingType = Enum.GetUnderlyingType(_enumType); ArrayList values = new ArrayList(); //List values = new List(); //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; } ///  /// Gets the values as a 'bindable' list datasource. ///This is a newer version of 'GetListValues()' ///  /// IList for data binding public IList GetGenericListValues() { Type underlyingType = Enum.GetUnderlyingType(_enumType); List values = new List(); //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; } ///  /// Return the existence of the given string value within the enum. ///  /// String value. /// Existence of the string value public bool IsStringDefined(string stringValue) { return Parse(_enumType, stringValue) != null; } ///  /// Return the existence of the given string value within the enum. ///  /// String value. /// Denotes whether to conduct a case-insensitive match on the supplied string value /// Existence of the string value public bool IsStringDefined(string stringValue, bool ignoreCase) { return Parse(_enumType, stringValue, ignoreCase) != null; } ///  /// Gets the underlying enum type for this instance. ///  ///  public Type EnumType { get { return _enumType; } } #endregion #region Static implementation ///  /// Gets a string value for a particular enum value. ///  /// Value. /// String Value associated via a  attribute, or null if not found. 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; } ///  /// Parses the supplied enum and string value to find an associated enum value (case sensitive). ///  /// Type. /// String value. /// Enum value associated with the string value, or null if not found. public static object Parse(Type type, string stringValue) { return Parse(type, stringValue, false); } ///  /// Parses the supplied enum and string value to find an associated enum value. ///  /// Type. /// String value. /// Denotes whether to conduct a case-insensitive match on the supplied string value /// Enum value associated with the string value, or null if not found. 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; } ///  /// Return the existence of the given string value within the enum. ///  /// String value. /// Type of enum /// Existence of the string value public static bool IsStringDefined(Type enumType, string stringValue) { return Parse(enumType, stringValue) != null; } ///  /// Return the existence of the given string value within the enum. ///  /// String value. /// Type of enum /// Denotes whether to conduct a case-insensitive match on the supplied string value /// Existence of the string value public static bool IsStringDefined(Type enumType, string stringValue, bool ignoreCase) { return Parse(enumType, stringValue, ignoreCase) != null; } #endregion } #endregion #region Class StringValueAttribute ///  /// Simple attribute class for storing String Values ///  public class StringValueAttribute : Attribute { private string _value; ///  /// Creates a new  instance. ///  /// Value. public StringValueAttribute(string value) { _value = value; } ///  /// Gets the value. ///  ///  public string Value { get { return _value; } } } #endregion } 

在枚举中定义Min和Max通常很有用,它始终是第一个和最后一个项目。 这是一个使用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; 

稍微“复杂”(可能是矫枉过正)但我使用这两种方法返回字典用作数据源。 第一个返回名称作为键,第二个值返回键。

 public static IDictionary  ConvertEnumToDictionaryNameFirst ()
 {
   if(typeof(K).BaseType!= typeof(Enum))
   {
    抛出新的InvalidCastException();
   }

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

或者你可以做到


 public static IDictionary  ConvertEnumToDictionaryValueFirst ()
 {
   if(typeof(K).BaseType!= typeof(Enum))
   {
    抛出新的InvalidCastException();
   }

  返回Enum.GetNames(typeof(K))。Cast ()。ToDictionary(currentItem) 
     =>(int)Enum.Parse(typeof(K),currentItem));
 }

这假设您使用的是3.5。 如果没有,你必须替换lambda表达式。

使用:


  字典列表= ConvertEnumToDictionaryValueFirst ();

  使用系统;
  使用System.Collections.Generic;
  使用System.Linq;