АвтоАвтоматизацияАрхитектураАстрономияАудитБиологияБухгалтерияВоенное делоГенетикаГеографияГеологияГосударствоДомДругоеЖурналистика и СМИИзобретательствоИностранные языкиИнформатикаИскусствоИсторияКомпьютерыКулинарияКультураЛексикологияЛитератураЛогикаМаркетингМатематикаМашиностроениеМедицинаМенеджментМеталлы и СваркаМеханикаМузыкаНаселениеОбразованиеОхрана безопасности жизниОхрана ТрудаПедагогикаПолитикаПравоПриборостроениеПрограммированиеПроизводствоПромышленностьПсихологияРадиоРегилияСвязьСоциологияСпортСтандартизацияСтроительствоТехнологииТорговляТуризмФизикаФизиологияФилософияФинансыХимияХозяйствоЦеннообразованиеЧерчениеЭкологияЭконометрикаЭкономикаЭлектроникаЮриспунденкция

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

Читайте также:
  1. Анализ атрибутов во время выполнения программы
  2. В нашем доме пожар? Создание театра медиа в период информационных войн
  3. Внешняя политика СССР в 1945-1885гг: изменения на международной арене, создание мировой социалистической системы, этапы холодной войны.
  4. Вопрос 7. Структура денежной массы. Создание денег банковской системой. Депозитный и денежный мультипликатор.
  5. Выделение сущностей и атрибутов из предметной области
  6. Глава 1 Создание специальных служб Финляндии 1914-1919гг.
  7. Задание 1. Создание запроса на выборку из двух таблиц с помощью мастера.
  8. Задание 1. Создание связи «один – ко – многим».
  9. Задание 1. Создание слайдов с анимацией.
  10. Задание 2. Создание вычисляемых полей в запросах.
  11. Задание 2. Создание нового поля с использованием подстановки значений из другой таблицы.
  12. Задание 2. Создание таблицы Документы МНТ

 

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 {}


1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 |

Поиск по сайту:



Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Студалл.Орг (0.006 сек.)