Заглавная страница Избранные статьи Случайная статья Познавательные статьи Новые добавления Обратная связь FAQ Написать работу КАТЕГОРИИ: АрхеологияБиология Генетика География Информатика История Логика Маркетинг Математика Менеджмент Механика Педагогика Религия Социология Технологии Физика Философия Финансы Химия Экология ТОП 10 на сайте Приготовление дезинфицирующих растворов различной концентрацииТехника нижней прямой подачи мяча. Франко-прусская война (причины и последствия) Организация работы процедурного кабинета Смысловое и механическое запоминание, их место и роль в усвоении знаний Коммуникативные барьеры и пути их преодоления Обработка изделий медицинского назначения многократного применения Образцы текста публицистического стиля Четыре типа изменения баланса Задачи с ответами для Всероссийской олимпиады по праву Мы поможем в написании ваших работ! ЗНАЕТЕ ЛИ ВЫ?
Влияние общества на человека
Приготовление дезинфицирующих растворов различной концентрации Практические работы по географии для 6 класса Организация работы процедурного кабинета Изменения в неживой природе осенью Уборка процедурного кабинета Сольфеджио. Все правила по сольфеджио Балочные системы. Определение реакций опор и моментов защемления |
Run-time retrieval of an attribute instanceСодержание книги
Поиск на нашем сайте
Compilation of an attribute yields an attribute class T, an instance constructor C on T, a positional-argument-list P, and a named-argument-list N. Given this information, an attribute instance can be retrieved at run-time using the following steps: · Follow the run-time processing steps for executing an object-creation-expression of the form new T(P), using the instance constructor C as determined at compile-time. These steps either result in an exception, or produce an instance O of T. · For each named-argument Arg in N, in order: o Let Name be the identifier of the named-argument Arg. If Name does not identify a non-static public read-write field or property on O, then an exception is thrown. o Let Value be the result of evaluating the attribute-argument-expression of Arg. o If Name identifies a field on O, then set this field to Value. o Otherwise, Name identifies a property on O. Set this property to Value. o The result is O, an instance of the attribute class T that has been initialized with the positional-argument-list P and the named-argument-list N. Reserved attributes A small number of attributes affect the language in some way. These attributes include: · System.AttributeUsageAttribute (§17.4.1), which is used to describe the ways in which an attribute class can be used. · System.Diagnostics.ConditionalAttribute (§17.4.2), which is used to define conditional methods. · System.ObsoleteAttribute (§17.4.3), which is used to mark a member as obsolete. · System.Runtime.CompilerServices.CallerLineNumberAttribute, System.Runtime.CompilerServices.CallerFilePathAttribute and System.Runtime.CompilerServices.CallerMemberNameAttribute (§17.4.4), which are used to supply information about the calling context to optional parameters. The AttributeUsage attribute The attribute AttributeUsage is used to describe the manner in which the attribute class can be used. A class that is decorated with the AttributeUsage attribute must derive from System.Attribute, either directly or indirectly. Otherwise, a compile-time error occurs. namespace System public virtual bool AllowMultiple { get {...} set {...} } public virtual bool Inherited { get {...} set {...} } public virtual AttributeTargets ValidOn { get {...} } public enum AttributeTargets All = Assembly | Module | Class | Struct | Enum | Constructor | The Conditional attribute The attribute Conditionalenables the definition of conditional methods and conditional attribute classes. namespace System.Diagnostics public string ConditionString { get {...} } Conditional methods A method decorated with the Conditional attribute is a conditional method. The Conditional attribute indicates a condition by testing a conditional compilation symbol. Calls to a conditional method are either included or omitted depending on whether this symbol is defined at the point of the call. If the symbol is defined, the call is included; otherwise, the call (including evaluation of the receiver and parameters of the call) is omitted. A conditional method is subject to the following restrictions: · The conditional method must be a method in a class-declaration or struct-declaration. A compile-time error occurs if the Conditional attribute is specified on a method in an interface declaration. · The conditional method must have a return type of void. · The conditional method must not be marked with the override modifier. A conditional method may be marked with the virtual modifier, however. Overrides of such a method are implicitly conditional, and must not be explicitly marked with a Conditional attribute. · The conditional method must not be an implementation of an interface method. Otherwise, a compile-time error occurs. In addition, a compile-time error occurs if a conditional method is used in a delegate-creation-expression. The example #define DEBUG using System; class Class1 class Class2 declares Class1.M as a conditional method. Class2's Test method calls this method. Since the conditional compilation symbol DEBUG is defined, if Class2.Test is called, it will call M. If the symbol DEBUG had not been defined, then Class2.Test would not call Class1.M. It is important to note that the inclusion or exclusion of a call to a conditional method is controlled by the conditional compilation symbols at the point of the call. In the example File class1.cs: using System.Diagnostics; class Class1 File class2.cs: #define DEBUG class Class2 File class3.cs: #undef DEBUG class Class3 the classes Class2 and Class3 each contain calls to the conditional method Class1.F, which is conditional based on whether or not DEBUG is defined. Since this symbol is defined in the context of Class2 but not Class3, the call to F in Class2 is included, while the call to F in Class3 is omitted. The use of conditional methods in an inheritance chain can be confusing. Calls made to a conditional method through base, of the form base.M, are subject to the normal conditional method call rules. In the example File class1.cs: using System; class Class1 File class2.cs: using System; class Class2: Class1 File class3.cs: #define DEBUG using System; class Class3 Class2 includes a call to the M defined in its base class. This call is omitted because the base method is conditional based on the presence of the symbol DEBUG, which is undefined. Thus, the method writes to the console “Class2.M executed” only. Judicious use of pp-declarations can eliminate such problems.
|
||||
Последнее изменение этой страницы: 2016-12-14; просмотров: 336; Нарушение авторского права страницы; Мы поможем в написании вашей работы! infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 3.145.83.149 (0.01 с.) |