MemberInfoExtensions.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using System.Linq;
  3. using System.Reflection;
  4. namespace Ips.Library.Basic
  5. {
  6. public static class MemberInfoExtensions
  7. {
  8. public static TAttribute GetSingleAttributeOrNull<TAttribute>(this MemberInfo memberInfo, bool inherit = true)
  9. where TAttribute : Attribute
  10. {
  11. if (memberInfo == null)
  12. {
  13. throw new ArgumentNullException(nameof(memberInfo));
  14. }
  15. var attrs = memberInfo.GetCustomAttributes(typeof(TAttribute), inherit).ToArray();
  16. if (attrs.Length > 0)
  17. {
  18. return (TAttribute)attrs[0];
  19. }
  20. return default;
  21. }
  22. public static TAttribute GetSingleAttributeOfTypeOrBaseTypesOrNull<TAttribute>(this Type type, bool inherit = true)
  23. where TAttribute : Attribute
  24. {
  25. var attr = type.GetTypeInfo().GetSingleAttributeOrNull<TAttribute>();
  26. if (attr != null)
  27. {
  28. return attr;
  29. }
  30. if (type.GetTypeInfo().BaseType == null)
  31. {
  32. return null;
  33. }
  34. return type.GetTypeInfo().BaseType.GetSingleAttributeOfTypeOrBaseTypesOrNull<TAttribute>(inherit);
  35. }
  36. }
  37. }