直接上代码:
namespace EnumStudy { public enum Days:byte//枚举继承什么类型就是什么类型 { [Description("星期1")] Monday=1, [Description("星期2")] Tuesday, [Description("星期3")] Wednesday, [Description("星期4")] Thursday, [Description("星期5")] Friday, [Description("星期6")] Saturday, [Description("星期7")] Sunday, } }
使用:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EnumStudy { public class UseerEnum { public void Run() { //枚举转字符串 string foo = Days.Saturday.ToString();//"Saturday" string foo1 = Enum.GetName(typeof(Days),6);//"Saturday" //字符串转枚举 Enum.TryParse("Saturday",out Days bar);//true,bar=Days.Saturday Days day = (Days)Enum.Parse(typeof(Days), "Saturday");// Days.Saturday //枚举转数字 byte foo2 = (byte)Days.Friday;//5 //数字转枚举 Days foo3=(Days)2;//Days.Tuesday //获取枚举所属类型 Type foo4 = Enum.GetUnderlyingType(typeof(Days)); //获取所有枚举成员 Array foo5 = Enum.GetValues(typeof(Days)); //获取所有枚举成员的字段名 string[] foo6 = Enum.GetNames(typeof(Days)); //默认值 Days d = (Days)21;//不会报错 Enum.IsDefined(typeof(Days), d);//false //枚举默认值永远为0 var z = default(Days); //获取枚举描述 string des = GetDescription(Days.Friday); } public string GetDescription(Enum val) { var field = val.GetType().GetField(val.ToString()); var customAttribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)); if (customAttribute == null) { return val.ToString(); } else { return ((DescriptionAttribute)customAttribute).Description; } } } }