3.14 Inspect the Attributes of a Program Element Using Reflection


3.14 Inspect the Attributes of a Program Element Using Reflection

Problem

You need to use reflection to inspect the custom attributes applied to a program element.

Solution

Call the GetCustomAttributes method on the System.Reflection.MemberInfo derived object that represents the program element you need to inspect.

Discussion

All of the classes that represent program elements derive from the MemberInfo class. This class includes Type , EventInfo , FieldInfo , PropertyInfo , and MethodBase . MethodBase has two further subclasses: ConstructorInfo and MethodInfo . If you obtain instances of any of these classes, you can call the inherited method GetCustomAttributes , which will return an object array containing the custom attributes applied to the program element. The object array contains only custom attributes, not those contained in the .NET Framework base class library.

The GetCustomAttributes method provides two overloads. The first takes a bool that controls whether GetCustomAttributes should return attributes inherited from parent classes. The second GetCustomAttributes overload takes an additional Type argument that acts as a filter, resulting in GetCustomAttributes returning only attributes of the specified type.

The following example uses the custom AuthorAttribute declared in recipe 3.13 and applies it to the GetCustomAttributesExample class. The Main method calls the GetCustomAttributes method, filtering the attributes so that the method returns only AuthorAttribute instances. You can safely cast this set of attributes to AuthorAttribute references and access their members without the need to use reflection.

 using System; [Author("Lena")] [Author("Allen", Company = "Principal Objective Ltd.")] public class GetCustomAttributesExample {     public static void Main() {         // Get a Type object for this class.          Type type = typeof(GetCustomAttributesExample);         // Get the attributes for the type. Apply a filter so that only         // instances of AuthorAttribute are returned.         object[] attrs =              type.GetCustomAttributes(typeof(AuthorAttribute), true);         // Enumerate the attributes and display their details.         foreach (AuthorAttribute a in attrs) {             Console.WriteLine(a.Name + ", " + a.Company);         }         // Wait to continue         Console.ReadLine();     } } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net