/// <summary> /// 擴展方法,獲得枚舉的Description /// </summary> /// <param name="value">枚舉值</param> /// <param name="nameInstead">當枚舉值沒有定義DescriptionAttribute,是否使用枚舉名代替,默認是使用</param> /// <returns>枚舉的Description</returns> public static string GetDescription<T>(Object value, String otherDesc = "", Boolean nameInstead = false) { var type = typeof(T); if (!type.IsEnum) { throw new ArgumentException("該對象不是一個枚舉類型!"); } string name = Enum.GetName(type, Convert.ToInt32(value)); if (name == null) { return otherDesc; } FieldInfo field = type.GetField(name); DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; if (attribute == null && nameInstead == true) { return name; } return attribute == null ? otherDesc : attribute.Description; } /// <summary> /// 把枚舉轉換為鍵值對集合 /// </summary> /// <param name="enumType">枚舉類型</param> /// <param name="getText">獲得值得文本</param> /// <returns>以枚舉值為key,枚舉文本為value的鍵值對集合</returns> public static Dictionary<Int32, String> EnumToDictionary<T>(EnumAppendItemType appendType = EnumAppendItemType.None) { var enumType = typeof(T); if (!enumType.IsEnum) { throw new ArgumentException("傳入的參數必須是枚舉類型!", "enumType"); } Dictionary<Int32, String> enumDic = new Dictionary<int, string>(); int appendId = Convert.ToInt16(appendType); if (appendType != EnumAppendItemType.None) { enumDic.Add(-999, GetDescription<EnumAppendItemType>(appendId)); } Array enumValues = Enum.GetValues(enumType); foreach (Enum enumValue in enumValues) { Int32 key = Convert.ToInt32(enumValue); String value = GetDescription<T>(key); enumDic.Add(key, value); } return enumDic; } public enum EnumAppendItemType { None = -999, [Description("--所有--")] All = 1, [Description("--請選擇--")] Select = 2, } /// /// 訪問設備 /// public enum DeviceType { [Description("PC")] PC=1, [Description("移動端")] Mobile = 2 }
使用方法:
EnumToDictionary<DeviceType>(EnumAppendItemType.All)
注:枚舉名是不能出現空格,()-/等字符