Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
20
Добавлен:
11.06.2015
Размер:
11 Мб
Скачать
☆

CHAPTER 24 REFLECTION AND ATTRIBUTES

What Is an Attribute?

An attribute is a language construct that allows you to add metadata to a program’s assembly. It’s a special type of class for storing information about program constructs.

•The program construct to which you apply an attribute is called its target.

•Programs designed to retrieve and use metadata, such as object browsers, are said to be consumers of the attributes.

•There are attributes that are predefined in .NET, and you can also declare custom attributes.

Figure 24-3 is an overview of the components involved in using attributes and illustrates the following points about them:

•You apply attributes to program constructs in the source code.

•The compiler takes the source code and produces metadata from the attributes and places that metadata in the assembly.

•Consumer programs can access the metadata of the attributes along with the metadata for the rest of the components of the program. Notice that the compiler both produces and consumes attributes.

Figure 24-3. The components involved with creating and using attributes

By convention, attribute names use Pascal casing and end with the suffix Attribute. When applying an attribute to a target, you can leave off the suffix. For example, for attributes SerializableAttribute and MyAttributeAttribute, you can use the short names Serializable and MyAttribute when applying them to a construct.

645

CHAPTER 24 REFLECTION AND ATTRIBUTES

Applying an Attribute

The purpose of an attribute is to tell the compiler to emit a certain set of metadata about a program construct to the assembly. You do this by applying the attribute to the construct.

•You apply an attribute by placing an attribute section immediately before the construct.

•An attribute section consists of square brackets enclosing an attribute name and sometimes a parameter list.

For example, the following code shows the headings of two classes. The first few lines of code show an attribute named Serializable applied to class MyClass. Notice that Serializable has no parameter list. The second class declaration has an attribute called MyAttribute, which has a parameter list with two string parameters.

[ Serializable ]

// Attribute

public class MyClass

 

{ ...

 

[ MyAttribute("Simple class", "Version 3.57") ]

// Attribute with parameters

public class MyOtherClass

 

{ ...

 

Some important things to know about attributes are the following:

•Most attributes apply only to the construct immediately following the attribute section or sections.

•A construct with an attribute applied to it is said to be decorated, or adorned, with the attribute. Both terms are common.

646

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]