03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

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

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

Exercises ❘ 599<br />

➤➤<br />

➤➤<br />

For each such class, the program should add an item to the Tools menu. The name of<br />

that item should be specified by the class’s DisplayName attribute. (If the class doesn’t<br />

have that attribute, use the class’s name.)<br />

Each Draw method should draw something on the Graphics object it is passed.<br />

Hint: To get a class’s DisplayName attribute value, get the class’s type and use the type’s<br />

GetCustomAttribute method. Cast the returned Attribute into a DisplayNameAttribute<br />

and use its DisplayName property.<br />

The following code shows an example add-in method.<br />

[DisplayName("Rectangle")]<br />

public static class RectangleDrawer<br />

{<br />

public static void Draw(Graphics gr)<br />

{<br />

// Draw something...<br />

}<br />

}<br />

Hint: When you find an appropriate Draw method, store its MethodInfo object in the Tag<br />

property of its menu item. That way when the user clicks that item, you can find the corresponding<br />

MethodInfo to invoke the method.<br />

4. The program you built for Exercise 3 looks for DLLs that hold classes that define a single Draw<br />

method. Alternatively, you could allow the classes to hold any number of add-in methods.<br />

Modify the program you wrote for Exercise 3 so it does that. It should use any method that<br />

takes a Graphics object as a parameter and that has a DisplayName attribute.<br />

5. The program you built for Exercise 4 assumes that any method that takes a Graphics object<br />

as a parameter and that has a DisplayName attribute is a drawing add-in. That works but is<br />

somewhat restrictive because it prevents you from having any other similar methods that are<br />

not add-ins. Another approach is to define your own custom attribute class and apply it to<br />

methods that are add-ins.<br />

Modify the program and DLL(s) you wrote for Exercise 4 to use this approach. In the DLL(s),<br />

create a DrawingAddInAttribute attribute class. Place it inside the DrawingAddIn namespace.<br />

(The rest of the DLL doesn’t need to be in that namespace.) The following code shows how you<br />

can create this attribute.<br />

namespace DrawingAddIn<br />

{<br />

// An attribute that flags a method as a drawing add-in tool.<br />

[AttributeUsage(AttributeTargets.Method)]<br />

public class DrawingAddInAttribute : Attribute<br />

{<br />

}<br />

}<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!