In C #, enumerations are handy for setting state values, for example, I define an enumeration called season
Public enum Season { Spring = 1, Summer = 2, Autumn = 3, Winter = 4 }
Enumeration names cannot appear spaces, ()-/characters
We want to display spring as spring, we have to define our own description information, we can use DescriptionAttribute, as follows
Public enum Season { [Description ("Spring")] spring = 1, [Description ("Summer")] Summer = 2, //[ Description ("Autumn")] Autumn = 3, [Description ("Winter")] Winter = 4 }
Let's write an extension method to get the enumeration's description information, as follows
//<summary>///extension method, get enumerated description///</summary>//<param name= "V Alue "> Enumeration value </param>//<param name=" Nameinstead "> If the enumeration value is not defined DescriptionAttribute, the enumeration name is used instead, the default is to use the </ param>///<returns> description</returns> public static string GetDescription for enumeration (this enum VA Lue, Boolean Nameinstead = True) {Type type = value. GetType (); String name = Enum.getname (type, value); if (name = = NULL) {return null; } FieldInfo field = Type. GetField (name); DescriptionAttribute attribute = attribute.getcustomattribute (field, typeof (DescriptionAttribute)) as DescriptionAttribute; if (attribute = = Null&&nameinstead = = True) {return name; } return attribute = = null? Null:attribute. Description; }
Converts an enumeration to a collection of key-value pairs
<summary>//// Convert the enumeration to a set of key-value pairs///</summary>// <param name= "enumtype" > Enum type </ param>// <param name= "GetText" > Get worthwhile text </param>// <returns> with enumeration value of key, Enumeration text is a key value pair collection </returns> public static Dictionary<int32 for value, string> enumtodictionary (Type enumtype, Func<enum, string> getText) { if (!enumtype.isenum) { throw new ArgumentException (" The parameter passed in must be an enumeration type! "," Enumtype "); } Dictionary<int32, string> enumdic = new Dictionary<int, string> (); Array enumvalues = enum.getvalues (enumtype); foreach (Enum enumvalue in EnumValues) { Int32 key = Convert.ToInt32 (enumvalue); String value = GetText (enumvalue); Enumdic.add (key, value); } return enumdic; }
C # defines DescriptionAttribute for enumerations, converts enumerations to key-value pairs