MemberInfoExtensions.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.Linq;
  3. using System.Reflection;
  4. namespace Abp.Reflection.Extensions
  5. {
  6. /// <summary>
  7. /// Extensions to <see cref="MemberInfo"/>.
  8. /// </summary>
  9. public static class MemberInfoExtensions
  10. {
  11. /// <summary>
  12. /// Gets a single attribute for a member.
  13. /// </summary>
  14. /// <typeparam name="TAttribute">Type of the attribute</typeparam>
  15. /// <param name="memberInfo">The member that will be checked for the attribute</param>
  16. /// <param name="inherit">Include inherited attributes</param>
  17. /// <returns>Returns the attribute object if found. Returns null if not found.</returns>
  18. public static TAttribute GetSingleAttributeOrNull<TAttribute>(this MemberInfo memberInfo, bool inherit = true)
  19. where TAttribute : Attribute
  20. {
  21. if (memberInfo == null)
  22. {
  23. throw new ArgumentNullException(nameof(memberInfo));
  24. }
  25. var attrs = memberInfo.GetCustomAttributes(typeof(TAttribute), inherit).ToArray();
  26. if (attrs.Length > 0)
  27. {
  28. return (TAttribute)attrs[0];
  29. }
  30. return default(TAttribute);
  31. }
  32. public static TAttribute GetSingleAttributeOfTypeOrBaseTypesOrNull<TAttribute>(this Type type, bool inherit = true)
  33. where TAttribute : Attribute
  34. {
  35. var attr = type.GetTypeInfo().GetSingleAttributeOrNull<TAttribute>();
  36. if (attr != null)
  37. {
  38. return attr;
  39. }
  40. if (type.GetTypeInfo().BaseType == null)
  41. {
  42. return null;
  43. }
  44. return type.GetTypeInfo().BaseType.GetSingleAttributeOfTypeOrBaseTypesOrNull<TAttribute>(inherit);
  45. }
  46. }
  47. }