Compartir a través de


Destinos de atributo (Extensiones de componentes de C++)

Los especificadores de uso de atributos permiten especificar los destinos del atributo. Cada atributo se define para aplicar a determinados elementos del lenguaje. Por ejemplo, un atributo se podría definir para aplicar a las clases y los structs. La lista siguiente se muestran los elementos sintácticos posibles en los que un atributo personalizado puede utilizarse. Las combinaciones de estos valores (mediante OR lógico) se pueden utilizar.

Para especificar el destino de atributo, para pasar uno o varios enumeradores de AttributeTargets a AttributeUsageAttribute al definir el atributo.

A continuación se muestra una lista de destinos válidos de atributo:

Destino

Uso del ejemplo

Todos

(se aplican a todas las construcciones)

// attribute_targets_all.cpp
// compile with: /clr /c
using namespace System;
[AttributeUsage(AttributeTargets::All)]
ref class Attr : public Attribute {};
[assembly:Attr];

Ensamblado

(se aplica a un ensamblado en conjunto)

// attribute_targets_assembly.cpp
// compile with: /clr /c
using namespace System;
[AttributeUsage(AttributeTargets::Assembly)]
ref class Attr : public Attribute {};
[assembly:Attr];

Module

(se aplica a un módulo de conjunto)

// attribute_targets_module.cpp
// compile with: /clr /c
using namespace System;
[AttributeUsage(AttributeTargets::Module)]
ref class Attr : public Attribute {};
[module:Attr];

Clase

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

Struct

// 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};

Constructor

// 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]
};

Método

// 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]
};

Propiedad

// 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]
};

Campo

// 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]
};

Evento

// 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]
};

Interfaz

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

Parámetro

// 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);
};

Delegate

// 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();

ReturnValue

// 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; }
};

Normalmente, un atributo precede directamente el elemento de lenguaje al que se aplica. Sin embargo, en algunos casos, la posición de un atributo no es suficiente para determinar el destino previsto del atributo. Considere este ejemplo:

[Attr] int MyFn(double x)...

Sintácticamente, no hay ninguna manera de saber si el atributo está diseñado para implementar el método o el valor devuelto del método (en este caso, tomará el método). En estos casos, un especificador de uso de atributos se puede utilizar. Por ejemplo, para que el atributo se aplica al valor devuelto, use el especificador de returnvalue , como sigue:

[returnvalue:Attr] int MyFn(double x)... // applies to return value

Requieren los especificadores de uso de atributos en las situaciones siguientes:

  • Para especificar un ensamblado ni módulo- nivel.

  • Para especificar que un atributo se aplica al valor devuelto de un método, no el método:

    [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
    
  • Para especificar que un atributo se aplica al descriptor de acceso de una propiedad, no la propiedad:

    [method:MyAttr(123)] property int Property()  
    [property:MyAttr(123)] property int Property()
    [MyAttr(123)] property int get_MyPropy() // default: property
    
  • Para especificar que un atributo se aplica al descriptor de acceso de un evento, no el evento:

    delegate void MyDel();
    ref struct X {
       [field:MyAttr(123)] event MyDel* MyEvent;   //field
       [event:MyAttr(123)] event MyDel* MyEvent;   //event
       [MyAttr(123)] event MyDel* MyEvent;   // default: event
    }
    

Un especificador de uso del atributo se aplica únicamente al atributo que le sigue inmediatamente; es decir,

[returnvalue:Attr1, Attr2]

es diferente de

[returnvalue:Attr1, returnvalue:Attr2]

Ejemplo

Descripción

Este ejemplo muestra cómo especificar varios destinos.

Código

// attribute_targets.cpp
// compile with: /clr /c
using namespace System;
[AttributeUsage(AttributeTargets::Class | AttributeTargets::Struct, AllowMultiple = true )]
ref struct Attr : public Attribute {
   Attr(bool i){}
   Attr(){}
};

[Attr]
ref class MyClass {};

[Attr]
[Attr(true)]
value struct MyStruct {};

Vea también

Referencia

Atributos definidos por el usuario (Extensiones de componentes de C++)