123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- namespace IoTIntegrationPlatform.Common
- {
- /// <summary>
- /// 枚举对象操作
- /// </summary>
- public static class EnumExtension
- {
- /// <summary>
- /// 获取枚举的描述信息
- /// </summary>
- public static string GetDescription(this Enum em)
- {
- Type type = em.GetType();
- FieldInfo fd = type.GetField(em.ToString());
- if (fd == null)
- {
- return string.Empty;
- }
- object[] attrs = fd.GetCustomAttributes(typeof(DescriptionAttribute), false);
- string name = string.Empty;
- foreach (DescriptionAttribute attr in attrs)
- {
- name = attr.Description;
- }
- return name;
- }
- /// <summary>
- /// 获取枚举值描述
- /// </summary>
- /// <param name="value"></param>
- /// <returns></returns>
- public static string GetEnumDescription(this Enum value)
- {
- FieldInfo fi = value.GetType().GetField(value.ToString());
- DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
- if (attributes != null && attributes.Length > 0)
- {
- return attributes[0].Description;
- }
- else
- {
- return value.ToString();
- }
- }
- ///// <summary>
- ///// 获取枚举值描述(无作用)
- ///// </summary>
- ///// <typeparam name="TEnum"></typeparam>
- ///// <param name="value"></param>
- ///// <returns></returns>
- //public static string GetDescription<TEnum>(this TEnum value) where TEnum : struct
- //{
- // return value.ToString(); // 默认返回枚举值的名称,这通常是最好的情况。如果枚举值没有自定义描述属性,将返回名称。
- //}
- /// <summary>
- /// 根据值获取枚举方法
- /// </summary>
- /// <param name="enumType"></param>
- /// <param name="value"></param>
- /// <returns></returns>
- public static Enum GetEnumByValue(Type enumType, string value)
- {
- return Enum.Parse(enumType, value) as Enum;
- }
- /// <summary>
- /// 获取枚举列表
- /// </summary>
- /// <param name="type"></param>
- /// <returns></returns>
- public static List<KeyValuePair<string, int>> GetEnumArray(this Type type)
- {
- var result = new List<KeyValuePair<string, int>>();
- if (type.IsEnum)
- {
- var values = Enum.GetValues(type);
- foreach (var item in values)
- {
- result.Add(new KeyValuePair<string, int>(((Enum)item).GetDescription(), (int)item));
- }
- }
- return result;
- }
- public static List<KeyValuePair<string, int>> GetEnumArray(this Type type, params Enum[] notinValue)
- {
- var result = new List<KeyValuePair<string, int>>();
- if (type.IsEnum)
- {
- var values = Enum.GetValues(type);
- foreach (var item in values)
- {
- if (notinValue.Contains((Enum)item))
- {
- continue;
- }
- result.Add(new KeyValuePair<string, int>(((Enum)item).GetDescription(), (int)item));
- }
- }
- return result;
- }
- }
- }
|