8.8. Runtime Discovery of Attributes Using Reflection

Now that we've decorated our classes with custom attributes, we'll want to access them during the execution of our program. There are several ways to do that. For example, we can invoke the static GetCustomAttributes() method of the Attribute class, passing it a Type object:

static public void retrieveClass1( object obj )
{
    Type tp = obj.GetType();

    Attribute [] attrs =
                 Attribute.GetCustomAttributes( tp );

An Attribute array holding an instance of each custom attribute retrieved is returned. If no custom attributes are present, an empty array is returned. Note that intrinsic attributes are not retrieved. For example, the intrinsic Serializable attribute of our class is not returned.

The instance GetCustomAttributes() method of the Type class can also be used. This method, however, returns a more general object array:

static public void retrieveClass2( object obj )
{
    Type tp = obj.GetType();
    object [] attrs = tp.GetCustomAttributes();

Both instances of GetCustomAttributes() return an array of all custom attributes associated with the type. If we are looking for a specific type, such as Author, we can use either the is operator or the as runtime operator:

Attribute [] attrs = Attribute.GetCustomAttributes( tp );

foreach( Attribute attr in attrs )
   if ( attr is AuthorAttribute )
   {
          AuthorAttribute auth = (AuthorAttribute) attr;
          Console.WriteLine(
                 "Author Attribute: {0} :: version {1:F}",
                 auth.name, auth.version );

          if ( auth.comment != null )
                 Console.WriteLine( "	{0}", auth.comment );
   }

Because we're interested in only the Author attribute, it would be simpler to retrieve only instances of that attribute. We do that by passing in a Type object of the attribute that interests us. An object array is returned filled with the matching instances, if any—for example,

static public void retrieveMembers( object obj )
{
    Type tp = obj.GetType();
    MemberInfo [] mi = tp.GetMembers();

    // prepare to select retrieval type
    Type attrType = Type.GetType( "AuthorAttribute" );

    foreach( MemberInfo m in mi )
    {
       // retrieve only AuthorAttribute instances
       object [] attrs = m.GetCustomAttributes( attrType );
    if ( attrs.Length == 0 )
           continue;

    foreach( object o in attrs )
    {
           string msg = "Author Attribute: {0} :: version {1:F}";
          AuthorAttribute auth = (AuthorAttribute) o;
           Console.WriteLine(msg, auth.name, auth.version);
          if ( auth.comment != null )
               Console.WriteLine( "	{0}", auth.comment );
    }
}

Intrinsic attributes are currently not retrievable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.111.208