using System; using System.Collections.Generic; using System.Linq; #if SIMPLSHARP using Crestron.SimplSharp.Reflection; #else using System.Reflection; #endif namespace ICD.Common.Utils.Extensions { /// /// Extension methods for use with reflection objects. /// public static class ReflectionExtensions { /// /// Returns the custom attributes attached to the member. /// /// /// /// public static IEnumerable GetCustomAttributes(this ICustomAttributeProvider extends) { if (extends == null) throw new ArgumentNullException("extends"); return extends.GetCustomAttributes(false); } /// /// Returns the custom attributes attached to the member. /// /// /// /// /// public static IEnumerable GetCustomAttributes(this ICustomAttributeProvider extends, bool inherits) { if (extends == null) throw new ArgumentNullException("extends"); try { return extends.GetCustomAttributes(typeof(T), inherits).Cast(); } // Crestron bug? catch (ArgumentNullException) { return Enumerable.Empty(); } } /// /// Returns the custom attribute attached to the member. /// /// /// /// public static T GetCustomAttribute(this ICustomAttributeProvider extends) { if (extends == null) throw new ArgumentNullException("extends"); return extends.GetCustomAttribute(false); } /// /// Returns the custom attribute attached to the member. /// /// /// /// /// public static T GetCustomAttribute(this ICustomAttributeProvider extends, bool inherits) { if (extends == null) throw new ArgumentNullException("extends"); return extends.GetCustomAttributes(inherits).First(); } #if NETSTANDARD /// /// Returns the custom attributes attached to the member. /// /// /// /// /// public static IEnumerable GetCustomAttributesIncludingBaseInterfaces(this Type extends) where T : Attribute { return extends.GetCustomAttributes(true) .Union(extends.GetInterfaces() .SelectMany(interfaceType => interfaceType .GetCustomAttributes(true))) .Distinct(); } /// /// Returns the custom attributes attached to the member. /// /// /// /// /// public static IEnumerable GetCustomAttributesIncludingBaseInterfaces(this MemberInfo extends) where T : Attribute { return extends.GetCustomAttributes(true) .Union(extends.DeclaringType? .GetInterfaces() .SelectMany(interfaceType => interfaceType .GetMember( extends.Name, extends.MemberType, BindingFlags.Instance) .FirstOrDefault()? .GetCustomAttributes(true) ?? Enumerable.Empty())? .Except(null) ?? Enumerable.Empty()) .Distinct(); } #endif } }