枚舉是一個指定的常數,其基礎類型能夠是除 Char 外的任何整型。
若是沒有顯式聲明基礎類型,則使用 Int32。
編程語言一般提供語法來聲明由一組已命名的常數和它們的值組成的枚舉。
定義默認基數從O開始,也可指定數值。編程
範例一:編程語言
enum Days { Saturday=1, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday }; enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }; Colors myColors = Colors.Red; string strColor=myColors.tostring(); int IntColor=(int)myColors ; //位或 Colors myColors = Colors.Red | Colors.Blue | Colors.Yellow; //位與 Colors myColors = Colors.Red & Colors.Blue & Colors.Yellow; //遍歷 foreach (string s in Enum.GetNames(typeof(Days))) Response.Write(s + "--" + Enum.Parse(typeof(Days), s).ToString()); //轉換 Colors mc=Colors Enum.Parse(typeof(Colors ), "red"); if (System.Enum.IsDefined(typeof(Days), "Monday")) Days ds= (Days)Enum.Parse(typeof(Days), "Monday");
範例二:this
public enum NoticeType { Notice = 'A', LabRule = 'H', HotInformation = 'N', Column = 'C', All = '1', Null = '0' } //新建枚舉類型 NoticeType noticeType1 = NoticeType.Column; //把枚舉類型轉換爲string d="Column" string d = noticeType1.ToString(); //取得枚舉類型的基數 dd='C' char dd = (char)noticeType1; //經過基數取得對應的枚舉類型 noticeType2 = NoticeType.Notice //(NoticeType)'A'; 兩種方式均可以 NoticeType noticeType2 = (NoticeType)Char.Parse("A"); //經過名稱取得枚舉類型 noticeType3 = NoticeType.Notice NoticeType noticeType3 = (NoticeType)Enum.Parse(typeof(NoticeType), "Notice");
得到文字描述:spa
using System.ComponentModel; // 先添加該引用 enum Direction { [Description("this means facing to UP (Negtive Y)")] UP = 1, [Description("this means facing to RIGHT (Positive X)")] RIGHT = 2, [Description("this means facing to DOWN (Positive Y)")] DOWN = 3, [Description("this means facing to LEFT (Negtive X)")] LEFT = 4 }; //使用以下方法來得到文字描述: using System.Reflection; using System.ComponentModel; public static String GetEnumDesc(Direction e) { FieldInfo EnumInfo = e.GetType().GetField(e.ToString()); DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[]) EnumInfo. GetCustomAttributes (typeof(DescriptionAttribute), false); if (EnumAttributes.Length > 0) { return EnumAttributes[0].Description; } return e.ToString(); }