namespace Zeta.EnterpriseLibrary.Tools { #region Using directives. // ---------------------------------------------------------------------- using System; // ---------------------------------------------------------------------- #endregion ///////////////////////////////////////////////////////////////////////// /// <summary> /// Helper methods for dealing with reflection. /// </summary> public sealed class ReflectionHelper { #region Access attributes. // ------------------------------------------------------------------ /// <summary> /// Check whether a certain attribute is associated with an object. /// </summary> /// <param name="o">The o.</param> /// <returns>Returns TRUE if present, FALSE if not.</returns> /// <typeparam name="T">The attribute to check.</typeparam> public static bool HasAttribute<T>( object o ) where T : Attribute { return GetAttribute<T>( o, null ) != null; } /// <summary> /// Read a certain attribute that is associated with an object. /// </summary> /// <param name="o">The object with the possible connected /// attribute.</param> /// <returns> /// Returns the attribute or NULL if not found. /// </returns> /// <typeparam name="T">The attribute to read.</typeparam> public static T GetAttribute<T>( object o ) where T : Attribute { return GetAttribute<T>( o, null ); } /// <summary> /// Read a certain attribute that is associated with an object. /// </summary> /// <param name="o">The object with the possible connected /// attribute.</param> /// <param name="fallBackValue">The value to use when not /// found.</param> /// <returns> /// Returns the attribute or the fall back value if not /// found. /// </returns> /// <typeparam name="T">The attribute to read.</typeparam> public static T GetAttribute<T>( object o, T fallBackValue ) where T : Attribute { if ( o == null ) { return fallBackValue; } else { if ( o is Enum ) { var fi = o.GetType().GetField( o.ToString() ); var attributes = (T[])fi.GetCustomAttributes( typeof( T ), false ); if ( attributes.Length > 0 ) { return attributes[0]; } else { return fallBackValue; } } else { var attributes = Attribute.GetCustomAttributes( o.GetType() ); if ( attributes == null || attributes.Length <= 0 ) { return fallBackValue; } else { foreach ( var attribute in attributes ) { if ( attribute is T ) { return attribute as T; } } return fallBackValue; } } } } // ------------------------------------------------------------------ #endregion } ///////////////////////////////////////////////////////////////////////// }
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)