/// <summary> ///Enumeration Extension Methods/// </summary> Public Static classenumextension {Private Staticdictionary<string, dictionary<string,string>>_enumcache; /// <summary> ///Cache/// </summary> Private Staticdictionary<string, dictionary<string,string>>Enumcache {Get{return_enumcache?? (_enumcache =Newdictionary<string, dictionary<string,string>>()); } Set{_enumcache =value;} } /// <summary> ///Get Enumeration Description information/// </summary> /// <param name= "en" ></param> /// <returns></returns> Public Static stringGetenumtext ( ThisSystem.Enum en) { stringEnstring =string. Empty; if(NULL= = en)returnenstring; Type type=en. GetType (); Enstring=en. ToString (); if(!Enumcache.containskey (type. FullName)) {system.reflection.fieldinfo[] fields=type. GetFields (); Dictionary<string,string> temp =Newdictionary<string,string>(); foreach(FieldInfo IteminchFields ) { Object[] Attrs = Item. GetCustomAttributes (typeof(Textattribute),false); if(Attrs. Length = =1) { stringv = ((Textattribute) attrs[0]). Value; Temp. ADD (item. Name, V); }} enumcache.add (type. FullName, temp); } if(Enumcache[type. FullName]. ContainsKey (enstring)) {returnEnumcache[type. Fullname][enstring]; } returnenstring; } /// <summary> ///iterate through all the elements of an enumeration object/// </summary> /// <typeparam name= "T" >Enumerating Objects</typeparam> /// <returns>Dictionary: Enumeration value-Description</returns> Public Staticdictionary<int,string> getenumvalues<t>() {Dictionary<int,string> dictionary =Newdictionary<int,string>(); foreach(varCodeinchSystem.Enum.GetValues (typeof(T))) {////Get Name //string strName = System.Enum.GetName (typeof (T), code); Object[] Objattrs = code. GetType (). GetField (code. ToString ()). GetCustomAttributes (typeof(Textattribute),true); if(Objattrs.length >0) {Textattribute descattr= objattrs[0] asTextattribute; if(!dictionary. ContainsKey ((int) (code)) {if(Descattr! =NULL) dictionary. ADD (int) code, Descattr.value); } //Console.WriteLine (String. Format ("[{0}]", Descattr.value)); } //Console.WriteLine (String. Format ("{0}={1}", code. ToString (), Convert.ToInt32 (code))); } returndictionary; } } /// <summary> ///Custom Description/// </summary> Public classTextattribute:attribute { PublicTextattribute (stringvalue) {Value=value; } /// <summary> ///Description Information/// </summary> Public stringValue {Get;Set; } }
C # Enumerates extension methods, gets the description value of an enumeration value, and gets all the elements under an enumeration class