C#枚举通用方法
1、定义枚举
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public enum ApplyState//例如:定义一个审核状态的枚举,包含以下几种状态 { /// <summary> /// 等待审批 /// </summary> [Description("等待审批")] WaitingForApproval = 1, /// <summary> /// 拒绝 /// </summary> [Description("拒绝")] Reject = 2, /// <summary> /// 审批通过 /// </summary> [Description("审批通过")] ApprovalThroughThe = 3, /// <summary> /// 取消申请 /// </summary> [Description("取消申请")] CancelApply = 4, }
2、通用方法类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class EnumHelper { /// <summary> /// 把枚举的描述和值绑定到DropDownList /// </summary> /// <param name="enumType"></param> /// <returns></returns> public static IEnumerable<SelectListItem> GetDataSoure(this Enum e) { List<SelectListItem> selectList = new List<SelectListItem>(); //获取字段信息 System.Reflection.FieldInfo[] ms = e.GetType().GetFields(); foreach (System.Reflection.FieldInfo f in ms) { //反射出自定义属性 foreach (Attribute attr in f.GetCustomAttributes(true)) { System.ComponentModel.DescriptionAttribute dscript = attr as System.ComponentModel.DescriptionAttribute; if (dscript != null) { selectList.Add(new SelectListItem() { Text = dscript.Description, Selected =(f.GetValue(e).ToString() == e.ToString()), Value = (f.GetValue(e)).ToString() }); } break; } } return selectList; } /// <summary> /// 获取枚举的描述文本 /// </summary> /// <param name="e">枚举成员</param> /// <returns></returns> public static string GetEnumDescription(this Enum e) { //获取字段信息 System.Reflection.FieldInfo[] ms = e.GetType().GetFields(); 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(); } }
3、枚举转化问题
1、枚举转Int (int)ApplyStatee.WaitingForApproval; 2、Int转枚举 (1)可以强制转换将整型转换成枚举类型:ApplyState state= (ApplyState)2;//找到值为2的枚举、即ApplyState.Reject (2)利用Enum的静态方法ToObject public static Object ToObject(Type enumType,int value) ApplyState state= (ApplyState)Enum.ToObject(typeof(ApplyState), 2),那么state即为ApplyState.Reject 3、字符串转枚举
ApplyState _Type = (ApplyState)Enum.Parse(typeof(ApplyState), "Reject"); 4、枚举转字符串 (1)枚举转字符串比较容易,可以直接用ToString()方法:例如:ApplyState.Reject.ToString() (2)利用Enum的静态方法GetName与GetNames: public static string GetName(Type enumType,Object value) public static string[] GetNames(Type enumType) 例如:Enum.GetName(typeof(ApplyState),2))与Enum.GetName(typeof(ApplyState), ApplyState.Reject))的值都是"Reject" Enum.GetNames(typeof(ApplyState))将返回枚举字符串数组
4、获取枚举的描述(Description)信息
调用上面的GetEnumDescription(Enum e)方法 例如:GetEnumDescription(ApplyState.Reject),得到的是"拒绝"