1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- 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 根据枚举值返回枚举对象
- /// <summary>
- /// 根据枚举值返回枚举对象
- /// </summary>
- /// <typeparam name="T">枚举类型</typeparam>
- /// <param name="val">枚举值</param>
- /// <returns>返回指定的枚举类型对象</returns>
- public static T GetEnumObj<T>(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<KeyValuePair<int, string>> GetEnumDescription(Type type)
- {
- List<KeyValuePair<int, string>> result = new List<KeyValuePair<int, string>>();
- 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, string>((int)field.GetRawConstantValue(), ((DescriptionAttribute)attrs[0]).Description));
- }
- }
- return result;
- }
- }
- }
|