Enumeration usage Summary
Use of enumeration in C #
1. In principle, enumeration is used in all cases. constants are not used unless constants are one, not a group.
2. If you want to modify the code after adding or removing constants in a group of constants, You need to define these constants as enumeration.
3. If the Code does not need to be modified after a constant is added or subtracted from a group of constants, store these constants in the primary file of the Code for database maintenance.
Enumeration Extension Method
1. Convert string to Enumeration
/// <Summary> /// convert the name of an enumeration item to an enumeration type /// </summary> /// <typeparam name = "TEnum"> </typeparam> /// <param name = "enumName"> name of the enumerated item </param> /// <returns> </returns> public static TEnum ToEnum <TEnum> (this string enumName) where TEnum: struct, IComparable, IFormattable, IConvertible {return (TEnum) Enum. parse (typeof (TEnum), enumName );}
2. Get the enumeration Description. Add the Description feature when defining the enumeration items.
/// <Summary> /// obtain the description of an enumerated value /// </summary> /// <param name = "obj"> enumerated value </param>/ // <returns> </returns> public static string GetDescription (this Enum obj) {FieldInfo fi = obj. getType (). getField (obj. toString (); DescriptionAttribute [] arrDesc = (DescriptionAttribute []) fi. getCustomAttributes (typeof (DescriptionAttribute), false); return arrDesc [0]. description ;}
3. Obtain the enumerated data list for easy binding to controls such as the drop-down list
/// <Summary> /// obtain the enumerated data list (description, name, value, it is usually used to bind to the control /// </summary> /// <typeparam name = "TEnum"> Enumeration type </typeparam> /// <returns> </returns> public static List <Tuple <string, string, int> GetEnumDataList <TEnum> () where TEnum: struct, IComparable, IFormattable, IConvertible {List <Tuple <string, string, int> dataList = new List <Tuple <string, string, int> (); Type t = typeof (TEnum); if (! T. isEnum) {return null;} Array arrays = Enum. getValues (t); for (int I = 0; I <arrays. longLength; I ++) {Enum tmp = (Enum) arrays. getValue (I); string description = GetDescription (tmp); string name = tmp. toString (); int value = Convert. toInt32 (tmp); dataList. add (new Tuple <string, string, int> (description, name, value);} return dataList ;}