C # Enumeration Action Tool class

Source: Internet
Author: User
<span style= "FONT-SIZE:14PX;" >using system;using system.collections.generic;using system.linq;using system.text;using System.Reflection;using System.componentmodel;using system.collections;using System.collections.specialized;namespace jiankunking.common.enumclass{//<summary>//Enumeration operation class///</summary> public static class Enumopera tion {#region Get description from the enumeration///<summary>///description///</summary        >//<param name= "Enumname" > Need to get Enumeration description enum </param>//<returns> Description of content </returns> public static string GetDescription (Enum enumname) {try {string _descript Ion = string.                Empty; FieldInfo _fieldinfo = Enumname.gettype ().                GetField (Enumname.tostring ());                descriptionattribute[] _attributes = getdescriptattr (_fieldinfo); if (_attributes! = null && _attributes.     Length > 0)           {_description = _attributes[0].                Description;                } else {_description = enumname.tostring ();            } return _description;            } catch (Exception) {throw;         }} #endregion #region get fields Description (private)///<summary>//Get fields description </summary>//<param name= "FieldInfo" >FieldInfo</param>//<returns>de Scriptionattribute[] </returns> private static descriptionattribute[] Getdescriptattr (This FieldInfo fieldinf O) {try {if (fieldInfo! = null) {return (                Descriptionattribute[]) fieldinfo.getcustomattributes (typeof (DescriptionAttribute), false);            } return null;          } catch (Exception)  {throw; }} #endregion #region get the enumeration definition string based on description///<summary>//Description Get Enumeration Definition string///</summary>//<typeparam name= "T" > Enum type </typeparam>//<param name= "D Escription "> Enumeration description </param>//<returns> enumeration </returns> public static T getenumname<t>        (String description)            {Type _type = typeof (T); foreach (FieldInfo field in _type. GetFields ()) {descriptionattribute[] _curdesc = field.                Getdescriptattr (); if (_curdesc! = null && _curdesc.length > 0) {if (_curdesc[0]. Description = = Description) {return (T) field.                    GetValue (NULL); }} or else {if field.               Name = = description) {         Return (T) field.                    GetValue (NULL); }}} throw new ArgumentException (string.        Format ("{0} could not find the corresponding enumeration.", description), "description");        #endregion #region Convert the enumeration to ArrayList////<summary>////Convert the enumeration to ArrayList///Description: Returns NULL if not an enumeration type//</summary>//<param name= "type" > Enum type </param>//&lt            ;returns>arraylist</returns> public static ArrayList toarraylist (type type) {try {if (type.                    Isenum) {ArrayList _array = new ArrayList ();                    Array _enumvalues = enum.getvalues (type); foreach (Enum value in _enumvalues) {_array.                    ADD (New Keyvaluepair<enum, string> (value, getdescription (value)));                } return _array;            }    return null;            } catch (Exception) {throw; }} #endregion #region based on the description of the enumeration worth to the attribute description, if this attribute is not defined returns an empty string//<summary>/ The enumeration is worth the description in the attribute description, and if this attribute is not defined returns an empty string//</summary>//<param name= "value" ></para m>//<param name= "enumtype" ></param>///<returns></returns> Publi C Static String getenumdescriptionstring (int value, Type enumtype) {try {Nam                Evaluecollection NVC = Getnvcfromenumvalue (enumtype); Return Nvc[value.            ToString ()];            } catch (Exception) {throw; }} #endregion #region get all of its values according to the enumeration type the collection of description attributes for the enumeration definition///<summary>// Gets all its values based on the enumeration type and the enumeration defines the collection of description properties.//</summary>//<param name= "Enumtype "></param>///<returns></returns> public static NameValueCollection GETNVC Fromenumvalue (Type enumtype) {try {NameValueCollection NVC = new Namevalueco                Llection ();                Type typedescription = typeof (DescriptionAttribute);                system.reflection.fieldinfo[] fields = Enumtype.getfields (); String strText = String.                Empty; String strvalue = String.                Empty; foreach (FieldInfo field) {if field. Fieldtype.isenum) {strvalue = ((int) enumtype.invokemember (field. Name, Bindingflags.getfield, NULL, NULL, or null)).                        ToString (); object[] arr = field.                        GetCustomAttributes (Typedescription, true); if (arr.   Length > 0) {descriptionattribute AA = (DescriptionAttribute) arr[0];                          StrText = AA.                        Description;                        } else {strText = ""; } NVC.                    ADD (strvalue, StrText);            }} return NVC;            } catch (Exception) {throw;          }} #endregion #region A corresponding enumeration definition string based on the enumeration value///<summary> </summary>//<param name= "value" ></param>//<param name= "Enumtype" ;</param>//<returns></returns> public static String getenumstring (int value, Type E Numtype) {try {NameValueCollection NVC = Getenumstringfromenumvalue (enumtype                ); Return Nvc[value.            ToString ()];          } catch (Exception) {      Throw }} #endregion #region A collection of all of its values and enumeration definition strings based on the enumeration type///<summary>////or by enumeration type A collection of all values with enumeration definition strings///</summary>//<param name= "enumtype" ></param>//&L        t;returns></returns> public static NameValueCollection Getenumstringfromenumvalue (Type enumtype)                {try {NameValueCollection NVC = new NameValueCollection ();                Type typedescription = typeof (DescriptionAttribute);                system.reflection.fieldinfo[] fields = Enumtype.getfields (); String strText = String.                Empty; String strvalue = String.                Empty; foreach (FieldInfo field) {if field. Fieldtype.isenum) {strvalue = ((int) enumtype.invokemember (field. Name, Bindingflags.getfield, NULL, NULL, or null)).            ToString ();            Nvc. Add (strvalue, field.                    Name);            }} return NVC;            } catch (Exception) {throw; }} #endregion}}</span>

If you know that the number of the enumeration is the number of the int type, get the name Direct strong turn (enum type) (int value)

Small bet
For the underlying public method class, it is best not to get the exception directly thrown, remember not to swallow or just throw some information.

The above is the contents of the C # Enumeration Operations Tool class, more relevant content please follow topic.alibabacloud.com (www.php.cn)!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.