15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

348 ❘ ChaPTer 14 reflectiOn<br />

Notice that the first thing you do in this method is check whether the Type reference you have been passed<br />

actually represents a class. Because, to keep things simple, you have specified that the LastModified<br />

attribute can be applied only to classes or member methods — you would be wasting your time by doing any<br />

processing if the item is not a class (it could be a class, delegate, or enum).<br />

Next, you use the Attribute.GetCustomAttributes() method to find out if this class has any<br />

LastModifiedAttribute instances attached to it. If it does, you add their details to the output text, using a<br />

helper method, WriteAttributeInfo().<br />

Finally, you use the Type.GetMethods() method to iterate through all the member methods of this<br />

data type, <strong>and</strong> then do the same with each method as you did for the class — check if it has any<br />

LastModifiedAttribute instances attached to it <strong>and</strong>, if so, display them using WriteAttributeInfo().<br />

The next bit of code shows the WriteAttributeInfo() method, which is responsible for working out<br />

what text to display for a given LastModifiedAttribute instance. Note that this method is passed an<br />

Attribute reference, so it needs to cast this to a LastModifiedAttribute reference first. After it has done<br />

that, it uses the properties that you originally defined for this attribute to retrieve its parameters. It checks<br />

that the date of the attribute is sufficiently recent before actually adding it to the text for display:<br />

private static void WriteAttributeInfo(Attribute attrib)<br />

{<br />

}<br />

LastModifiedAttribute lastModifiedAttrib =<br />

attrib as LastModifiedAttribute;<br />

if (lastModifiedAttrib == null)<br />

{<br />

return;<br />

}<br />

// check that date is in range<br />

DateTime modifiedDate = lastModifiedAttrib.DateModified;<br />

if (modifiedDate < backDateTo)<br />

{<br />

return;<br />

}<br />

AddToMessage(" MODIFIED: " +<br />

modifiedDate.ToLongDateString() + ":");<br />

AddToMessage(" " + lastModifiedAttrib.Changes);<br />

if (lastModifiedAttrib.Issues != null)<br />

{<br />

AddToMessage(" Outst<strong>and</strong>ing issues:" +<br />

lastModifiedAttrib.Issues);<br />

}<br />

Finally, here is the helper AddToMessage() method:<br />

}<br />

}<br />

static void AddToMessage(string message)<br />

{<br />

outputText.Append("\n" + message);<br />

}<br />

Running this code produces the results shown in Figure 14-2.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!