AttributeUtils.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using JiaZhiQuan.Common.Attributes;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. namespace JiaZhiQuan.Common.Utils
  7. {
  8. /// <summary>
  9. /// 特性工具类
  10. /// </summary>
  11. public static class AttributeUtils
  12. {
  13. /// <summary>
  14. /// 获取枚举字段的特性
  15. /// </summary>
  16. /// <param name="value"></param>
  17. /// <returns></returns>
  18. public static T GetEnumDescription<T>(System.Enum value) where T : Attribute
  19. {
  20. var type = value.GetType();
  21. var name = System.Enum.GetName(type, value);
  22. if (name == null) return null;
  23. var field = type.GetField(name);
  24. if (field == null) return null;
  25. return Attribute.GetCustomAttribute(field, typeof(T)) as T;
  26. }
  27. /// <summary>
  28. /// 获取枚举字段的特性
  29. /// </summary>
  30. /// <typeparam name="TEnum">枚举</typeparam>
  31. /// <typeparam name="TAttribute">特性</typeparam>
  32. /// <param name="func"></param>
  33. /// <returns></returns>
  34. public static List<TAttribute> FindEnumValues<TEnum, TAttribute>(Func<TAttribute, bool> func)
  35. where TEnum : System.Enum
  36. where TAttribute : Attribute
  37. {
  38. List<TAttribute> attributes = new List<TAttribute>();
  39. var fields = typeof(TEnum).GetFields(bindingAttr: BindingFlags.Public | BindingFlags.Static);
  40. fields.ForEach(e =>
  41. {
  42. // 获取枚举字段的特性
  43. var attribute = Attribute.GetCustomAttribute(e, typeof(TAttribute)) as TAttribute;
  44. if (func(attribute))
  45. {
  46. attributes.Add(attribute);
  47. }
  48. });
  49. return attributes;
  50. }
  51. }
  52. }