Is there a way to iterate through all enum values?
Possible Duplicate:
C#: How to enumerate an enum?
主题是"全部"。我想用它在组合框中添加枚举的值。
谢谢
维克伯格
1 |
然后用数组填充下拉列表
我知道其他人已经用正确的答案回答了问题,但是,如果您想使用组合框中的枚举,您可能需要使用额外的码,并将字符串关联到枚举,以便在显示的字符串中提供更详细的信息(例如,单词之间的空格或使用与您的编码字符串不匹配的大小写显示字符串)。安德斯)
此日志可能有用-将字符串与C中的枚举关联#
1 2 3 4 5 6 7 8 9 10 11 12 | public enum States { California, [Description("New Mexico")] NewMexico, [Description("New York")] NewYork, [Description("South Carolina")] SouthCarolina, Tennessee, Washington } |
作为额外的好处,他还提供了一个实用方法来枚举枚举枚举,我现在用jon skeet的注释更新了这个枚举。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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; } |
乔恩还指出,在C 3.0中,可以将其简化为类似的内容(现在重量越来越轻,我想您可以直接进行此操作):
1 2 3 4 5 6 7 8 9 10 11 |
使用Enum.GetValues方法:
1 2 3 4 |
您不需要将它们强制转换为字符串,这样您就可以通过将SelectedItem属性直接强制转换为TestEnum值来检索它们。
您可以迭代Enum.GetNames方法返回的数组。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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); } } |
如果需要组合的值与枚举的值相对应,也可以使用如下内容:
1 2 3 4 |
通过这种方式,您可以在下拉列表中显示文本并返回值(在SelectedValue属性中)
.NET 3.5通过使用扩展方法使其变得简单:
1 | enum Color {Red, Green, Blue} |
可以迭代
1 |
或定义新的静态泛型方法:
1 2 3 |
请记住,使用enum.getValues()方法进行迭代使用反射,因此会对性能造成影响。
使用枚举填充下拉列表的问题是,枚举中不能有奇怪的字符或空格。我有一些扩展枚举的代码,这样你就可以添加任何你想要的字符。
像这样使用……
1 2 3 4 5 6 7 8 | 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, } |
像这样绑定数据。
1 2 |
这是扩展枚举的类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | // 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 2 3 4 5 6 7 8 9 10 |
或者你可以做
1 2 3 4 5 6 7 8 9 10 |
但这假设您使用的是3.5。如果不是,则必须替换lambda表达式。
用途:
1 | Dictionary list = ConvertEnumToDictionaryValueFirst<SomeEnum>(); |
1 2 3 | using System; using System.Collections.Generic; using System.Linq; |
在枚举中定义最小值和最大值通常很有用,这将始终是第一个和最后一个项。下面是一个使用Delphi语法的非常简单的示例:
1 2 3 4 5 6 7 8 9 10 | 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; |