RSS Feed (xml)

Inspect the Attributes of a Program Element Using Reflection

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  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("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

No comments:

Post a Comment

Archives In Web World

Fun Mail - Fun in the Mail