15.01.2013 Views

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

3. Write one or more public constructors. The parameters to the constructor define<br />

the positional parameters of the attribute and will become mandatory when<br />

using the attribute.<br />

4. Declare a public field or property for each named parameter you wish to support.<br />

Named parameters are optional when using the attribute.<br />

Attribute properties and constructor parameters must be of the<br />

following types:<br />

• A sealed primitive type: in other words, bool, byte, char,<br />

double, float, int, long, short, or string<br />

• The Type type<br />

• An enum type<br />

• A one-dimensional array of any of these<br />

When an attribute is applied, it must also be possible for the<br />

compiler to statically evaluate each of the properties or constructor<br />

arguments.<br />

The following class defines an attribute for assisting an automated unit-testing system.<br />

It indicates that a method should be tested, the number of test repetitions, and<br />

a message in case of failure:<br />

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

public sealed class TestAttribute : Attribute<br />

{<br />

public int Repetitions;<br />

public string FailureMessage;<br />

public TestAttribute () : this (1) { }<br />

public TestAttribute (int repetitions) { Repetitions = repetitions; }<br />

}<br />

Here’s a Foo class with methods decorated in various ways with the Test attribute:<br />

class Foo<br />

{<br />

[Test]<br />

public void Method1() { ... }<br />

[Test(20)]<br />

public void Method2() { ... }<br />

[Test(20, FailureMessage="Debugging Time!")]<br />

public void Method3() { ... }<br />

}<br />

704 | Chapter 18: Reflection and Metadata

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

Saved successfully!

Ooh no, something went wrong!