using System; using System.Linq; using System.Reflection; namespace Ips.Library.Basic { public static class MemberInfoExtensions { public static TAttribute GetSingleAttributeOrNull(this MemberInfo memberInfo, bool inherit = true) where TAttribute : Attribute { if (memberInfo == null) { throw new ArgumentNullException(nameof(memberInfo)); } var attrs = memberInfo.GetCustomAttributes(typeof(TAttribute), inherit).ToArray(); if (attrs.Length > 0) { return (TAttribute)attrs[0]; } return default; } public static TAttribute GetSingleAttributeOfTypeOrBaseTypesOrNull(this Type type, bool inherit = true) where TAttribute : Attribute { var attr = type.GetTypeInfo().GetSingleAttributeOrNull(); if (attr != null) { return attr; } if (type.GetTypeInfo().BaseType == null) { return null; } return type.GetTypeInfo().BaseType.GetSingleAttributeOfTypeOrBaseTypesOrNull(inherit); } } }