Целевые объекты атрибутов (расширения компонентов C++)
Статья
Описатели использования атрибута позволяют определить целевые объекты атрибута. Каждый атрибут определен для применения к определенным элементам языка. Например, атрибут может быть задан для применения только для классов и структур. В следующем списке показаны возможные синтаксические элементы, на которых можно использовать настраиваемый атрибут. Могут использоваться сочетания из этих значений (с помощью логических или).
Для определения целевого объекта атрибута, для передачи одного или нескольких перечислителей AttributeTargets в AttributeUsageAttribute при указании атрибута.
Ниже приведен список допустимых целевых объектов атрибута.
Целевой объект
Использование образца
Все
(применяется ко всем конструкциям)
// attribute_targets_all.cpp
// compile with: /clr /c
using namespace System;
[AttributeUsage(AttributeTargets::All)]
ref class Attr : public Attribute {};
[assembly:Attr];
Сборка
(применяется к сборке в целом)
// attribute_targets_assembly.cpp
// compile with: /clr /c
using namespace System;
[AttributeUsage(AttributeTargets::Assembly)]
ref class Attr : public Attribute {};
[assembly:Attr];
Module
(применяется к модулю в целом)
// attribute_targets_module.cpp
// compile with: /clr /c
using namespace System;
[AttributeUsage(AttributeTargets::Module)]
ref class Attr : public Attribute {};
[module:Attr];
Класс
// attribute_targets_class.cpp
// compile with: /clr /c
using namespace System;
[AttributeUsage(AttributeTargets::Class)]
ref class Attr : public System::Attribute {};
[Attr] // same as [class:Attr]
ref class MyClass {};
Структура
// attribute_targets_struct.cpp
// compile with: /clr /c
using namespace System;
[AttributeUsage(AttributeTargets::Struct)]
ref class Attr : public Attribute {};
[Attr] // same as [struct:Attr]
value struct MyStruct{};
enum
// attribute_targets_enum.cpp
// compile with: /clr /c
using namespace System;
[AttributeUsage(AttributeTargets::Enum)]
ref class Attr : public Attribute {};
[Attr] // same as [enum:Attr]
enum struct MyEnum{e, d};
Конструктор
// attribute_targets_constructor.cpp
// compile with: /clr /c
using namespace System;
[AttributeUsage(AttributeTargets::Constructor)]
ref class Attr : public Attribute {};
ref struct MyStruct{
[Attr] MyStruct(){} // same as [constructor:Attr]
};
Метод
// attribute_targets_method.cpp
// compile with: /clr /c
using namespace System;
[AttributeUsage(AttributeTargets::Method)]
ref class Attr : public Attribute {};
ref struct MyStruct{
[Attr] void Test(){} // same as [method:Attr]
};
Свойство
// attribute_targets_property.cpp
// compile with: /clr /c
using namespace System;
[AttributeUsage(AttributeTargets::Property)]
ref class Attr : public Attribute {};
ref struct MyStruct{
[Attr] property int Test; // same as [property:Attr]
};
Поле
// attribute_targets_field.cpp
// compile with: /clr /c
using namespace System;
[AttributeUsage(AttributeTargets::Field)]
ref class Attr : public Attribute {};
ref struct MyStruct{
[Attr] int Test; // same as [field:Attr]
};
Событие
// attribute_targets_event.cpp
// compile with: /clr /c
using namespace System;
[AttributeUsage(AttributeTargets::Event)]
ref class Attr : public Attribute {};
delegate void ClickEventHandler(int, double);
ref struct MyStruct{
[Attr] event ClickEventHandler^ OnClick; // same as [event:Attr]
};
Интерфейс
// attribute_targets_interface.cpp
// compile with: /clr /c
using namespace System;
[AttributeUsage(AttributeTargets::Interface)]
ref class Attr : public Attribute {};
[Attr] // same as [event:Attr]
interface struct MyStruct{};
Параметр
// attribute_targets_parameter.cpp
// compile with: /clr /c
using namespace System;
[AttributeUsage(AttributeTargets::Parameter)]
ref class Attr : public Attribute {};
ref struct MyStruct{
void Test([Attr] int i);
void Test2([parameter:Attr] int i);
};
Делегат
// attribute_targets_delegate.cpp
// compile with: /clr /c
using namespace System;
[AttributeUsage(AttributeTargets::Delegate)]
ref class Attr : public Attribute {};
[Attr] delegate void Test();
[delegate:Attr] delegate void Test2();
Возвращаемое значение
// attribute_targets_returnvalue.cpp
// compile with: /clr /c
using namespace System;
[AttributeUsage(AttributeTargets::ReturnValue)]
ref class Attr : public Attribute {};
ref struct MyStruct {
// Note required specifier
[returnvalue:Attr] int Test() { return 0; }
};
Обычно атрибут непосредственно предшествует элементу языка, к которому он применяется. Однако в некоторых случаях положения атрибута недостаточно для определения предполагаемого целевого объекта. Рассмотрим следующий пример.
[Attr] int MyFn(double x)...
Синтаксически, не существует способа определить, должен ли атрибут применяться к методу или к возвращаемому значению метода (в этом случае по умолчанию в метод). В таких случаях может быть использован описатель использования атрибута. Например, чтобы заставить атрибут применяться к возвращаемому значению, используйте описатель returnvalue следующим образом:
[returnvalue:Attr] int MyFn(double x)... // applies to return value
Описатели использования атрибута необходимы в следующих случаях:
Для определения атрибута уровня сборки или модуля.
Указать, что атрибут применяется к возвращаемому значению метода, а не к методу:
[method:Attr] int MyFn(double x)... // Attr applies to method
[returnvalue:Attr] int MyFn(double x)...// Attr applies to return value
[Attr] int MyFn(double x)... // default: method
Указать, что атрибут применяется к методам доступа свойства, а не к свойству.
[method:MyAttr(123)] property int Property()
[property:MyAttr(123)] property int Property()
[MyAttr(123)] property int get_MyPropy() // default: property
Указать, что атрибут применяется к методу доступу события, а не к событию: