using System; using System.Collections.Generic; using System.Web.Mvc; namespace Common { public class EnumHelper { /// /// 把枚举的描述和值绑定到DropDownList /// /// /// public static List GetCategorySelectList(Type enumType, bool addAll = true, object value = null) { List selectList = new List(); if (addAll) { selectList.Add(value == null ? new SelectListItem { Text = "--请选择--", Value = "", Selected = true } : new SelectListItem { Text = "--请选择--", Value = "" }); } foreach (object e in System.Enum.GetValues(enumType)) { if (value != null && ((int)e) == (decimal)value) { selectList.Add(new SelectListItem { Text = GetEnumDescription(e), Value = ((int)e).ToString(), Selected = true }); } else { selectList.Add(new SelectListItem { Text = GetEnumDescription(e), Value = ((int)e).ToString() }); } } return selectList; } /// /// 把枚举的描述和字面值绑定到DropDownList /// /// /// public static List GetCategorySelectTextList(Type enumType, bool addAll = true, object value = null) { List selectList = new List(); if (addAll) { selectList.Add(value == null ? new SelectListItem { Text = "--请选择--", Value = "", Selected = true } : new SelectListItem { Text = "--请选择--", Value = "" }); } foreach (object e in Enum.GetValues(enumType)) { if (value != null && e.ToString() == value.ToString()) { selectList.Add(new SelectListItem { Text = GetEnumDescription(e), Value = e.ToString(), Selected = true }); } else { selectList.Add(new SelectListItem { Text = GetEnumDescription(e), Value = e.ToString() }); } } return selectList; } /// /// /// /// /// /// public static string ConvertToE(string strValue) where T : struct, IConvertible { if (!string.IsNullOrEmpty(strValue)) { T t; return System.Enum.TryParse(strValue, true, out t) ? t.ToString() : ""; } return string.Empty; } /// /// 将字符串转换为枚举类型 /// /// /// /// public static T? ConvertToEnum(string strValue) where T : struct, IConvertible { T t; if (System.Enum.TryParse(strValue, true, out t)) { return t; } return null; } /// /// 根据枚举字面值返回描述文件 /// /// /// /// public static string GetDesc(object e) where T : struct, IConvertible { if (e == null) { return ""; } return GetEnumDescription(e); } /// /// 获取枚举的描述文本 /// /// 枚举成员 /// private static string GetEnumDescription(object e) { //获取字段信息 System.Reflection.FieldInfo[] ms = e.GetType().GetFields(); //Type t = e.GetType(); foreach (System.Reflection.FieldInfo f in ms) { //判断名称是否相等 if (f.Name != e.ToString()) continue; //反射出自定义属性 foreach (Attribute attr in f.GetCustomAttributes(true)) { //类型转换找到一个Description,用Description作为成员名称 System.ComponentModel.DescriptionAttribute dscript = attr as System.ComponentModel.DescriptionAttribute; if (dscript != null) return dscript.Description; } } //如果没有检测到合适的注释,则用默认名称 return e.ToString(); } } }