Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

Создание пользовательских атрибутов

Упаковка и разупаковка данных | Типы данных со значением null | Конструкторы и деструкторы | Частично определяемые классы и их назначение | Механизм вызова событий | Создание пользовательских обобщенных коллекций | Создание обобщенных интерфейсов | Установка ограничений на параметры обобщенных классов | Обобщенные делегаты | Несколько слов о вложенных делегатах |


Читайте также:
  1. A. Создание персонажей
  2. I. Создание визитной карточки
  3. I. Создание информационного трехстраничного буклета
  4. I. Создание Энергетического и Духовного Тел
  5. MS PowerPoint. Создание слайда с диаграммой и таблицей
  6. MS PowerPoint. Создание управляющих кнопок
  7. VBA7. Сортировка чисел в столбце по возрастанию или убыванию с созданием формы и панели инструментов с кнопкой

 

A class that derives from the abstract class System.Attribute, whether directly or indirectly, is an attribute class. The declaration of an attribute class defines a new kind of attribute that can be placed on a declaration. By convention, attribute classes are named with a suffix of Attribute. Uses of an attribute may either include or omit this suffix.

The attribute AttributeUsage is used to describe how an attribute class can be used.

AttributeUsage has a positional parameter that enables an attribute class to specify the kinds of declarations on which it can be used. The example

 

using System;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)]
public class SimpleAttribute: Attribute
{
...
}

defines an attribute class named SimpleAttribute that can be placed on class-declarations and interface-declarations only.

 

[Simple] class Class1 {...}

[SimpleAttribute] interface Interface1 {...}

AttributeUsage has a named parameter called AllowMultiple, which indicates whether the attribute can be specified more than once for a given entity. If AllowMultiple for an attribute class is true, then that attribute class is a multi-use attribute class, and can be specified more than once on an entity. If AllowMultiple for an attribute class is false or it is unspecified, then that attribute class is a single-use attribute class, and can be specified at most once on an entity.

 

using System;

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class AuthorAttribute: Attribute
{
private string name;

public AuthorAttribute(string name) {
this.name = name;
}

public string Name {
get { return name; }
}
}

defines a multi-use attribute class named AuthorAttribute. The example

[Author("Brian Kernighan"), Author("Dennis Ritchie")]
class Class1
{
...
}

shows a class declaration with two uses of the Author attribute.

 

AttributeUsage has another named parameter called Inherited, which indicates whether the attribute, when specified on a base class, is also inherited by classes that derive from that base class. If Inherited for an attribute class is true, then that attribute is inherited. If Inherited for an attribute class is false then that attribute is not inherited. If it is unspecified, its default value is true.

 

An attribute class X not having an AttributeUsage attribute attached to it, as in

using System;

class X: Attribute {...}

is equivalent to the following:

using System;

[AttributeUsage(
AttributeTargets.All,
AllowMultiple = false,
Inherited = true)
]
class X: Attribute {...}

Attribute classes can have positional parameters and named parameters. Each public instance constructor for an attribute class defines a valid sequence of positional parameters for that attribute class. Each non-static public read-write field and property for an attribute class defines a named parameter for the attribute class.

 

using System;

[AttributeUsage(AttributeTargets.Class)]
public class HelpAttribute: Attribute
{
public HelpAttribute(string url) { // Positional parameter
...
}

public string Topic { // Named parameter
get {...}
set {...}
}

public string Url {
get {...}
}
}

defines an attribute class named HelpAttribute that has one positional parameter, url, and one named parameter, Topic. Although it is non-static and public, the property Url does not define a named parameter, since it is not read-write.

 

This attribute class might be used as follows:

 

[Help("http://www.mycompany.com/.../Class1.htm")]
class Class1
{
...
}

[Help("http://www.mycompany.com/.../Misc.htm", Topic = "Class2")]
class Class2
{
...
}

An attribute consists of an attribute-name and an optional list of positional and named arguments. The positional arguments (if any) precede the named arguments. A positional argument consists of an attribute-argument-expression; a named argument consists of a name, followed by an equal sign, followed by an attribute-argument-expression, which, together, are constrained by the same rules as simple assignment. The order of named arguments is not significant.

 

In other contexts, inclusion of an attribute-target-specifier is permitted but unnecessary. For instance, a class declaration may either include or omit the specifier type:

 

[type: Author("Brian Kernighan")]
class Class1 {}

[Author("Dennis Ritchie")]
class Class2 {}

It is an error to specify an invalid attribute-target-specifier. For instance, the specifier param cannot be used on a class declaration:

 

[param: Author("Brian Kernighan")] // Error
class Class1 {}

By convention, attribute classes are named with a suffix of Attribute. An attribute-name of the form type-name may either include or omit this suffix. If an attribute class is found both with and without this suffix, an ambiguity is present, and a compile-time error results. If the attribute-name is spelled such that its right-most identifier is a verbatim identifier, then only an attribute without a suffix is matched, thus enabling such an ambiguity to be resolved.

 

The example

 

using System;

[AttributeUsage(AttributeTargets.All)]
public class X: Attribute
{}

[AttributeUsage(AttributeTargets.All)]
public class XAttribute: Attribute
{}

[X] // Error: ambiguity
class Class1 {}

[XAttribute] // Refers to XAttribute
class Class2 {}

[@X] // Refers to X
class Class3 {}

[@XAttribute] // Refers to XAttribute
class Class4 {}

shows two attribute classes named X and XAttribute. The attribute [X] is ambiguous, since it could refer to either X or XAttribute. Using a verbatim identifier allows the exact intent to be specified in such rare cases. The attribute [XAttribute] is not ambiguous (although it would be if there was an attribute class named XAttributeAttribute!). If the declaration for class X is removed, then both attributes refer to the attribute class named XAttribute, as follows:

using System;

[AttributeUsage(AttributeTargets.All)]
public class XAttribute: Attribute
{}

[X] // Refers to XAttribute
class Class1 {}

[XAttribute] // Refers to XAttribute
class Class2 {}

[@X] // Error: no attribute named "X"
class Class3 {}

It is a compile-time error to use a single-use attribute class more than once on the same entity.

 

An expression E is an attribute-argument-expression if all of the following statements are true:

The type of E is an attribute parameter type.

At compile-time, the value of E can be resolved to one of the following:

· A constant value.

· A System.Type object.

· A one-dimensional array of attribute-argument-expressions.

For example:

using System;

[AttributeUsage(AttributeTargets.Class)]
public class TestAttribute: Attribute
{
public int P1 {
get {...}
set {...}
}

public Type P2 {
get {...}
set {...}
}

public object P3 {
get {...}
set {...}
}
}

[Test(P1 = 1234, P3 = new int[] {1, 3, 5}, P2 = typeof(float))]
class MyClass {}


Дата добавления: 2015-11-16; просмотров: 70 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
И напоследок... блок finally| Анализ атрибутов во время выполнения программы

mybiblioteka.su - 2015-2024 год. (0.008 сек.)