|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
AttributesIn most programming languages, some information is expressed through declaration, and other information is expressed through code. For example, in the following class member declaration public int Test; the compiler and runtime will reserve space for an integer variable and set its protection so that it is visible everywhere. This is an example of declarative information; it's nice because of the economy of expression and because the compiler handles the details for us. Typically, the types of declarative information are predefined by the language designer and can't be extended by users of the language. A user who wants to associate a specific database field with a field of a class, for example, must invent a way of expressing that relationship in the language, a way of storing the relationship, and a way of accessing the information at runtime. In a language like C++, a macro might be defined that stores the information in a field that is part of the object. Such schemes work, but they're error-prone and not generalized. They're also ugly. The .NET Runtime supports attributes, which are merely annotations that are placed on elements of source code, such as classes, members, parameters, etc. Attributes can be used to change the behavior of the runtime, provide transaction information about an object, or convey organizational information to a designer. The attribute information is stored with the metadata of the element and can be easily retrieved at runtime through a process known as reflection. C# uses a conditional attribute to control when member functions are called. A use for the conditional attribute would look like this: using System.Diagnostics;
class Test
{
[Conditional("DEBUG")]
public void Validate()
{
}
}
Most programmers will use predefined attributes much more often than writing an attribute class. Using AttributesSuppose that for a project that a group was doing, it was important to keep track of the code reviews that had been performed on the classes so that it could be determined when code reviews were finished. The code review information could be stored in a database, which would allow easy queries about status, or it could be stored in comments, which would make it easy to look at the code and the information at the same time. Or an attribute could be used, which would enable both kinds of access. To do that, an attribute class is needed. An attribute class defines the name of an attribute, how it can be created, and the information that will be stored. The gritty details of defining attribute classes will be covered in the section entitled "An Attribute of Your Own." The attribute class will look like this: using System;
[AttributeUsage(AttributeTargets.Class)]
public class CodeReviewAttribute: System.Attribute
{
public CodeReviewAttribute(string reviewer, string date)
{
this.reviewer = reviewer;
this.date = date;
}
public string Comment
{
get
{
return(comment);
}
set
{
comment = value;
}
}
public string Date
{
get
{
return(date);
}
}
public string Reviewer
{
get
{
return(reviewer);
}
}
string reviewer;
string date;
string comment;
}
[CodeReview("Eric", "01-12-2000", Comment="Bitchin' Code")]
class Complex
{
}
The The naming convention for attributes is to append The class defines a single constructor that takes a reviewer and a date as parameters, and it also has the public string When the compiler comes to the attribute usage on class Next, it checks to see whether the attribute is allowed on a class. Then, it checks to see if there is a constructor that matches the parameters we've specified in the attribute use. If it finds one, an instance of the object is created—the constructor is called with the specified values. If there are named parameters, it matches the name of the parameter with a field or property in the attribute class, and then it sets the field or property to the specified value. After this is done, the current state of the attribute class is saved to the metadata for the program element for which it was specified. At least, that's what happens logically. In actuality, it only looks like it happens that way; see the "Attribute Pickling" sidebar for a description of how it is implemented. A Few More DetailsSome attributes can only be used once on a given element. Others, known as multi-use attributes, can be used more than once. This might be used, for example, to apply several different security attributes to a single class. The documentation on the attribute will describe whether an attribute is single-use or multi-use. In most cases, it's clear that the attribute applies to a specific program element. However, consider the following case: class Test
{
[ReturnsHResult]
public void Execute()
{}
}
In most cases, an attribute in that position would apply to the member function, but this attribute is really related to the return type. How can the compiler tell the difference? There are several situations in which this can happen:
For each of these situations, there is a case that is much more common than the other case, and it becomes the default case. To specify an attribute for the non-default case, the element the attribute applies to must be specified: class Test
{
[return:ReturnsHResult]
public void Execute()
{}
}
The The element may be specified even if there is no ambiguity. The identifiers are as follows:
Attributes that are applied to assemblies or modules must occur after any using System;
[assembly:CLSCompliant(true)]
class Test
{
Test() {}
}
This example applies the To use a predefined attribute, start by finding the constructor that best matches the information to be conveyed. Next, write the attribute, passing parameters to the constructor. Finally, use the named parameter syntax to pass additional information that wasn't part of the constructor parameters. For more examples of attribute use, look at Chapter 29, "Interop."
An Attribute of Your OwnTo define attribute classes and reflect on them at runtime, there are a few more issues to consider. This section will discuss some things to consider when designing an attribute. There are two major things to determine when writing an attribute. The first is the program elements that the attribute may be applied to, and the second is the information that will be stored by the attribute. Attribute UsagePlacing the
As part of the The [AttributeUsage(AttributeTargets.Method | AttributeTargets.Event,
AllowMultiple = true)]
Attribute ParametersThe information the attribute will store should be divided into two groups: the information that is required for every use, and the optional items. The information that is required for every use should be obtained via the constructor for the attribute class. This forces the user to specify all the parameters when they use the attribute. Optional items should be implemented as named parameters, which allows the user to specify whichever optional items are appropriate. If an attribute has several different ways in which it can be created, with different required information, separate constructors can be declared for each usage. Don't use separate constructors as an alternative to optional items. Attribute Parameter TypesThe attribute pickling format only supports a subset of all the .NET Runtime types, and therefore, only some types can be used as attribute parameters. The types allowed are the following:
Reflecting on AttributesOnce attributes are defined on some code, it's useful to be able to find the attribute values. This is done through reflection. The following code shows an attribute class, the application of the attribute to a class, and the reflection on the class to retrieve the attribute. using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.Class)]
public class CodeReviewAttribute: System.Attribute
{
public CodeReviewAttribute(string reviewer, string date)
{
this.reviewer = reviewer;
this.date = date;
}
public string Comment
{
get
{
return(comment);
}
set
{
comment = value;
}
}
public string Date
{
get
{
return(date);
}
}
public string Reviewer
{
get
{
return(reviewer);
}
}
string reviewer;
string date;
string comment;
}
[CodeReview("Eric", "01-12-2000", Comment="Bitchin' Code")]
class Complex
{
}
class Test
{
public static void Main()
{
System.Reflection.MemberInfo info;
info = typeof(Complex);
object[] atts;
atts = info.GetCustomAttributes(typeof(CodeReviewAttribute));
if (atts.GetLength(0) != 0)
{
CodeReviewAttribute att = (CodeReviewAttribute) atts[0];
Console.WriteLine("Reviewer: {0}", att.Reviewer);
Console.WriteLine("Date: {0}", att.Date);
Console.WriteLine("Comment: {0}", att.Comment);
}
}
}
The This example produces the following output: Reviewer: Eric
Date: 01-12-2000
Comment: Bitchin' Code
Note: The " Copyright © 2000 APress
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||