|
|||||||
АвтоАвтоматизацияАрхитектураАстрономияАудитБиологияБухгалтерияВоенное делоГенетикаГеографияГеологияГосударствоДомДругоеЖурналистика и СМИИзобретательствоИностранные языкиИнформатикаИскусствоИсторияКомпьютерыКулинарияКультураЛексикологияЛитератураЛогикаМаркетингМатематикаМашиностроениеМедицинаМенеджментМеталлы и СваркаМеханикаМузыкаНаселениеОбразованиеОхрана безопасности жизниОхрана ТрудаПедагогикаПолитикаПравоПриборостроениеПрограммированиеПроизводствоПромышленностьПсихологияРадиоРегилияСвязьСоциологияСпортСтандартизацияСтроительствоТехнологииТорговляТуризмФизикаФизиологияФилософияФинансыХимияХозяйствоЦеннообразованиеЧерчениеЭкологияЭконометрикаЭкономикаЭлектроникаЮриспунденкция |
Создание пользовательских атрибутов
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)] 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 AuthorAttribute(string name) { public string Name { defines a multi-use attribute class named AuthorAttribute. The example [Author("Brian Kernighan"), Author("Dennis Ritchie")] 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( 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 string Topic { // Named parameter public string Url { 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")] [Help("http://www.mycompany.com/.../Misc.htm", Topic = "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")] [Author("Dennis Ritchie")] 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 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)] [AttributeUsage(AttributeTargets.All)] [X] // Error: ambiguity [XAttribute] // Refers to XAttribute [@X] // Refers to X [@XAttribute] // Refers to XAttribute 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)] [X] // Refers to XAttribute [XAttribute] // Refers to XAttribute [@X] // Error: no attribute named "X" 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 Type P2 { public object P3 { [Test(P1 = 1234, P3 = new int[] {1, 3, 5}, P2 = typeof(float))] Поиск по сайту: |
Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Студалл.Орг (0.006 сек.) |