using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Chernobyl.Collections.Generic; namespace Chernobyl.Reflection { /// /// Extension and utility methods for . /// public static class CustomAttributeProviderExtensions { /// /// Returns the custom /// attribute instances defined on this member or an empty /// if there are no custom attributes of /// that type. Effectively, this method does the exact same thing as /// . /// /// The type of the attribute /// instances to return. /// The instance to retrieve the attribute /// instances from. /// When true, look up the hierarchy chain for the /// inherited custom attributes. /// The attribute instances defined on /// . public static IEnumerable GetCustomAttributes( this ICustomAttributeProvider provider, bool inherit) { return provider.GetCustomAttributes(typeof(TAttribute), inherit) .Cast(); } /// /// Returns the custom /// attribute instance defined on this member or null if there are no /// custom attributes of that type. Effectively, this method does the /// exact same thing as /// . /// /// The type of the attribute /// instance to return. /// The instance to retrieve the /// attribute instance from. /// When true, look up the hierarchy chain for the /// inherited custom attribute. /// The attribute instance defined on /// or null if there is no attribute of type /// . public static TAttribute GetCustomAttribute( this ICustomAttributeProvider provider, bool inherit) { return provider.GetCustomAttributes(inherit) .FirstOrDefault(); } /// /// Returns true if the specified /// has an attribute of the type specified by . /// /// The instance to check for the attribute. /// The type of attribute to check for on /// the instance. /// When true, look up the hierarchy chain for the /// inherited custom attribute. /// True if the provider has the attribute, false if otherwise. public static bool HasAttribute(this ICustomAttributeProvider provider, Type attributeType, bool inherit) { return provider.GetCustomAttributes(attributeType, inherit) .IsEmpty() == false; } /// /// Returns true if the specified /// has an attribute of the type specified by . /// /// The type of attribute to check for on /// the instance. /// The instance to check for the attribute. /// When true, look up the hierarchy chain for the /// inherited custom attribute. /// True if the provider has the attribute, false if otherwise. public static bool HasAttribute(this ICustomAttributeProvider provider, bool inherit) { return provider.HasAttribute(typeof (TAttribute), inherit); } } }