public enum Season { Spring = 1, Summer = 2, Autumn = 3, Winter = 4 }
枚舉名是不能出現空格,()-/等字符
我們想把Spring顯示為春天,我們要自己定義說明信息,我們可以使用DescriptionAttribute,如下
public enum Season { [Description("春 天")] Spring = 1, [Description("夏 天")] Summer = 2, //[Description("秋 天")] Autumn = 3, [Description("冬 天")] Winter = 4 }
下面我們來寫個擴展方法,來得到枚舉的說明信息,如下
/// <summary> /// 擴展方法,獲得枚舉的Description /// </summary> /// <param name="value">枚舉值</param> /// <param name="nameInstead">當枚舉值沒有定義DescriptionAttribute,是否使用枚舉名代替,默認是使用</param> /// <returns>枚舉的Description</returns> public static string GetDescription(this Enum value, 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; }
把枚舉轉換為鍵值對集合
/// <summary> /// 把枚舉轉換為鍵值對集合 /// </summary> /// <param name="enumType">枚舉類型</param> /// <param name="getText">獲得值得文本</param> /// <returns>以枚舉值為key,枚舉文本為value的鍵值對集合</returns> public static Dictionary<Int32, String> EnumToDictionary(Type enumType, Func<Enum, String> getText) { if (!enumType.IsEnum) { throw new ArgumentException("傳入的參數必須是枚舉類型!", "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; }
我們把上面兩個方法放入名為EnumUtil的靜態類中。
下面是使用方法
public enum Season { [Description("春 天")] Spring = 1, [Description("夏 天")] Summer = 2, //[Description("秋 天")] Autumn = 3, [Description("冬 天")] Winter = 4 } class Program { static void Main(string[] args) { Season spring = Season.Spring; //打印枚舉名 Console.WriteLine(spring.ToString()); //打印枚舉說明 Console.WriteLine(spring.GetDescription()); //枚舉轉換為鍵值對集合 Dictionary<Int32, String> dic = EnumUtil.EnumToDictionary(typeof(Season), e => e.GetDescription()); PrintDic(dic); dic = EnumUtil.EnumToDictionary(typeof(Season), e => e.GetDescription(false)); PrintDic(dic); dic = EnumUtil.EnumToDictionary(typeof(Season), e => e.ToString());