using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace NX_CommonClassLibrary { public static class EnumExtensionHelper { #region 根据枚举值返回枚举对象 /// /// 根据枚举值返回枚举对象 /// /// 枚举类型 /// 枚举值 /// 返回指定的枚举类型对象 public static T GetEnumObj(object val) where T : Enum { FieldInfo[] fields = typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public); bool isGet = false; foreach (var fi in fields) { int enumVal = ((int)fi.GetValue(null)); int tmpVal = Convert.ToInt32(val); if (enumVal == tmpVal) { isGet = true; break; } } if (isGet) { val = Convert.ToInt32(val); return (T)val; } else { return (T)fields[0].GetValue(null); } } public static object GetEnumObj1(object val,Type t) { FieldInfo[] fields = t.GetFields(BindingFlags.Static | BindingFlags.Public); bool isGet = false; foreach (var fi in fields) { int enumVal = ((int)fi.GetValue(null)); int tmpVal = Convert.ToInt32(val); if (enumVal == tmpVal) { isGet = true; break; } } if (isGet) { val = Convert.ToInt32(val); return val; } else { return fields[0].GetValue(null); } } #endregion public static IEnumerable> GetEnumDescription(Type type) { List> result = new List>(); if (!type.IsEnum) return result; var fields = type.GetFields(); foreach (var field in fields) { object[] attrs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); if (null != attrs && attrs.Length > 0) { result.Add(new KeyValuePair((int)field.GetRawConstantValue(), ((DescriptionAttribute)attrs[0]).Description)); } } return result; } } }