Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.
Traducción
Inglés

Clase CustomAttributeData

 

Publicado: octubre de 2016

Proporciona acceso a los datos de atributos personalizados para los ensamblados, los módulos, los tipos, los miembros y los parámetros cargados en el contexto de solo reflexión.

Espacio de nombres:   System.Reflection
Ensamblado:  mscorlib (en mscorlib.dll)

System.Object
  System.Reflection.CustomAttributeData

[SerializableAttribute]
[ComVisibleAttribute(true)]
public class CustomAttributeData

NombreDescripción
System_CAPS_protmethodCustomAttributeData()

Inicializa una nueva instancia de la clase CustomAttributeData.

NombreDescripción
System_CAPS_pubpropertyAttributeType

Obtiene el tipo del atributo.

System_CAPS_pubpropertyConstructor

Obtiene un objeto ConstructorInfo que representa el constructor que habría inicializado el atributo personalizado.

System_CAPS_pubpropertyConstructorArguments

Obtiene la lista de argumentos posicionales especificado para la instancia del atributo representada por la CustomAttributeData objeto.

System_CAPS_pubpropertyNamedArguments

Obtiene la lista de argumentos con nombre especificados para la instancia del atributo representada por la CustomAttributeData objeto.

NombreDescripción
System_CAPS_pubmethodEquals(Object)

Devuelve un valor que indica si esta instancia equivale al objeto especificado. (Invalida Object.Equals(Object)).

System_CAPS_protmethodFinalize()

Permite que un objeto intente liberar recursos y realizar otras operaciones de limpieza antes de ser reclamado por el recolector de basura. (Heredado de Object).

System_CAPS_pubmethodSystem_CAPS_staticGetCustomAttributes(Assembly)

Devuelve una lista de objetos CustomAttributeData que representan datos sobre los atributos que se aplicaron al ensamblado de destino.

System_CAPS_pubmethodSystem_CAPS_staticGetCustomAttributes(MemberInfo)

Devuelve una lista de objetos CustomAttributeData que representan datos sobre los atributos que se aplicaron al miembro de destino.

System_CAPS_pubmethodSystem_CAPS_staticGetCustomAttributes(Module)

Devuelve una lista genérica de objetos CustomAttributeData que representan datos sobre los atributos que se aplicaron al módulo de destino.

System_CAPS_pubmethodSystem_CAPS_staticGetCustomAttributes(ParameterInfo)

Devuelve una lista genérica de objetos CustomAttributeData que representan datos sobre los atributos que se aplicaron al parámetro de destino.

System_CAPS_pubmethodGetHashCode()

Actúa como función hash para un tipo concreto.(Invalida Object.GetHashCode()).

System_CAPS_pubmethodGetType()

Obtiene el Type de la instancia actual.(Heredado de Object).

System_CAPS_protmethodMemberwiseClone()

Crea una copia superficial del Object actual.(Heredado de Object).

System_CAPS_pubmethodToString()

Devuelve una representación de cadena del atributo personalizado.(Invalida Object.ToString()).

Code that is being examined in the reflection-only context cannot be executed, so it is not always possible to examine custom attributes by creating instances of them and then examining their properties, using methods like Overload:System.Attribute.GetCustomAttributes, Overload:System.Reflection.MemberInfo.GetCustomAttributes, and so on. If the code for the attribute type itself is loaded into the reflection-only context, it cannot be executed.

The T:System.Reflection.CustomAttributeData class allows examination of custom attributes in the reflection-only context by providing an abstraction for attributes. The members of this class can be used to obtain the positional arguments and named arguments of the attribute. Use the P:System.Reflection.CustomAttributeData.ConstructorArguments property to get a list of T:System.Reflection.CustomAttributeTypedArgument structures that represent the positional arguments, and use the P:System.Reflection.CustomAttributeData.NamedArguments property to get a list of T:System.Reflection.CustomAttributeNamedArgument structures that represent the named arguments.

System_CAPS_noteNota

The T:System.Reflection.CustomAttributeNamedArgument structure only provides information about the attribute property used to get and set the argument value. To obtain the type and value of the argument, use the P:System.Reflection.CustomAttributeNamedArgument.TypedValue property to obtain a T:System.Reflection.CustomAttributeTypedArgument structure.

When you have a T:System.Reflection.CustomAttributeTypedArgument structure for an argument, whether named or positional, use the P:System.Reflection.CustomAttributeTypedArgument.ArgumentType property to get the type and the P:System.Reflection.CustomAttributeTypedArgument.Value property to get the value.

System_CAPS_noteNota

For an array argument, the P:System.Reflection.CustomAttributeTypedArgument.Value property returns a generic T:System.Collections.ObjectModel.ReadOnlyCollection`1 of T:System.Reflection.CustomAttributeTypedArgument objects. Each T:System.Reflection.CustomAttributeTypedArgument object in the collection represents the corresponding element of the array.

CustomAttributeData can be used in the execution context as well as in the reflection-only context. For example, you might want to avoid loading the assembly that contains the code for a custom attribute. Using the CustomAttributeData class is different from using methods like Attribute.GetCustomAttributes:

  • The properties and methods of T:System.Reflection.CustomAttributeData only provide you with the values that were specified for the attribute instance, not the semantics of the constructor. For example, a string argument of an attribute might be converted internally to some other representation, and returned in a canonical form; or a property might have side effects when the actual attribute code is executed.

  • The properties and methods of T:System.Reflection.CustomAttributeData do not allow you to retrieve the custom attributes inherited from base classes.

To create instances of the T:System.Reflection.CustomAttributeData class, use the static (Shared in Visual Basic) Overload:System.Reflection.CustomAttributeData.GetCustomAttributes factory methods.

The following example defines a custom attribute with four constructors and four properties. Two of the properties are read-only, and are set by using the positional parameters of the constructors. The other two properties are read/write, and can be set only by using named arguments. One positional property is an array of strings, and one named property is an array of integers.

The attribute is applied to the assembly, to a type declared in the assembly, to a method of the type, and to a parameter of the method. Different constructors are used for these cases. When executed, the assembly loads itself into the reflection-only context and displays information about the custom attributes that were applied to it and to the type and members it contains.

The attribute that is applied to the type demonstrates array properties, with both positional and named arguments.

using System;
using System.Reflection;
using System.Collections.Generic;
using System.Collections.ObjectModel;

// The example attribute is applied to the assembly.
[assembly:Example(ExampleKind.ThirdKind, Note="This is a note on the assembly.")]

// An enumeration used by the ExampleAttribute class.
public enum ExampleKind
{
    FirstKind, 
    SecondKind, 
    ThirdKind, 
    FourthKind
};

// An example attribute. The attribute can be applied to all
// targets, from assemblies to parameters.
//
[AttributeUsage(AttributeTargets.All)]
public class ExampleAttribute : Attribute
{
    // Data for properties.
    private ExampleKind kindValue;
    private string noteValue;
    private string[] arrayStrings;
    private int[] arrayNumbers;

    // Constructors. The parameterless constructor (.ctor) calls
    // the constructor that specifies ExampleKind and an array of 
    // strings, and supplies the default values.
    //
    public ExampleAttribute(ExampleKind initKind, string[] initStrings)
    {
        kindValue = initKind;
        arrayStrings = initStrings;
    }
    public ExampleAttribute(ExampleKind initKind) : this(initKind, null) {}
    public ExampleAttribute() : this(ExampleKind.FirstKind, null) {}

    // Properties. The Note and Numbers properties must be read/write, so they
    // can be used as named parameters.
    //
    public ExampleKind Kind { get { return kindValue; }}
    public string[] Strings { get { return arrayStrings; }}
    public string Note    
    {
        get { return noteValue; }
        set { noteValue = value; }
    }
    public int[] Numbers
    {
        get { return arrayNumbers; }
        set { arrayNumbers = value; }
    }
}

// The example attribute is applied to the test class.
//
[Example(ExampleKind.SecondKind, 
         new string[] { "String array argument, line 1", 
                        "String array argument, line 2", 
                        "String array argument, line 3" }, 
         Note="This is a note on the class.",
         Numbers = new int[] { 53, 57, 59 })] 
public class Test
{
    // The example attribute is applied to a method, using the
    // parameterless constructor and supplying a named argument.
    // The attribute is also applied to the method parameter.
    //
    [Example(Note="This is a note on a method.")]
    public void TestMethod([Example] object arg) { }

    // Main() gets objects representing the assembly, the test
    // type, the test method, and the method parameter. Custom
    // attribute data is displayed for each of these.
    //
    public static void Main()
    {
        Assembly asm = Assembly.ReflectionOnlyLoad("Source");
        Type t = asm.GetType("Test");
        MethodInfo m = t.GetMethod("TestMethod");
        ParameterInfo[] p = m.GetParameters();

        Console.WriteLine("\r\nAttributes for assembly: '{0}'", asm);
        ShowAttributeData(CustomAttributeData.GetCustomAttributes(asm));
        Console.WriteLine("\r\nAttributes for type: '{0}'", t);
        ShowAttributeData(CustomAttributeData.GetCustomAttributes(t));
        Console.WriteLine("\r\nAttributes for member: '{0}'", m);
        ShowAttributeData(CustomAttributeData.GetCustomAttributes(m));
        Console.WriteLine("\r\nAttributes for parameter: '{0}'", p);
        ShowAttributeData(CustomAttributeData.GetCustomAttributes(p[0]));
    }

    private static void ShowAttributeData(
        IList<CustomAttributeData> attributes)
    {
        foreach( CustomAttributeData cad in attributes )
        {
            Console.WriteLine("   {0}", cad);
            Console.WriteLine("      Constructor: '{0}'", cad.Constructor);

            Console.WriteLine("      Constructor arguments:");
            foreach( CustomAttributeTypedArgument cata 
                in cad.ConstructorArguments )
            {
                ShowValueOrArray(cata);
            }

            Console.WriteLine("      Named arguments:");
            foreach( CustomAttributeNamedArgument cana 
                in cad.NamedArguments )
            {
                Console.WriteLine("         MemberInfo: '{0}'", 
                    cana.MemberInfo);
                ShowValueOrArray(cana.TypedValue);
            }
        }
    }

    private static void ShowValueOrArray(CustomAttributeTypedArgument cata)
    {
        if (cata.Value.GetType() == typeof(ReadOnlyCollection<CustomAttributeTypedArgument>))
        {
            Console.WriteLine("         Array of '{0}':", cata.ArgumentType);

            foreach (CustomAttributeTypedArgument cataElement in 
                (ReadOnlyCollection<CustomAttributeTypedArgument>) cata.Value)
            {
                Console.WriteLine("             Type: '{0}'  Value: '{1}'",
                    cataElement.ArgumentType, cataElement.Value);
            }
        }
        else
        {
            Console.WriteLine("         Type: '{0}'  Value: '{1}'", 
                cata.ArgumentType, cata.Value);
        }
    }
}

/* This code example produces output similar to the following:

Attributes for assembly: 'source, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
   [System.Runtime.CompilerServices.CompilationRelaxationsAttribute((Int32)8)]
      Constructor: 'Void .ctor(Int32)'
      Constructor arguments:
         Type: 'System.Int32'  Value: '8'
      Named arguments:
   [System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows = True)]
      Constructor: 'Void .ctor()'
      Constructor arguments:
      Named arguments:
         MemberInfo: 'Boolean WrapNonExceptionThrows'
         Type: 'System.Boolean'  Value: 'True'
   [ExampleAttribute((ExampleKind)2, Note = "This is a note on the assembly.")]
      Constructor: 'Void .ctor(ExampleKind)'
      Constructor arguments:
         Type: 'ExampleKind'  Value: '2'
      Named arguments:
         MemberInfo: 'System.String Note'
         Type: 'System.String'  Value: 'This is a note on the assembly.'

Attributes for type: 'Test'
   [ExampleAttribute((ExampleKind)1, new String[3] { "String array argument, line 1", "String array argument, line 2", "String array argument, line 3" }, Note = "This is a note on the class.", Numbers = new Int32[3] { 53, 57, 59 })]
      Constructor: 'Void .ctor(ExampleKind, System.String[])'
      Constructor arguments:
         Type: 'ExampleKind'  Value: '1'
         Array of 'System.String[]':
             Type: 'System.String'  Value: 'String array argument, line 1'
             Type: 'System.String'  Value: 'String array argument, line 2'
             Type: 'System.String'  Value: 'String array argument, line 3'
      Named arguments:
         MemberInfo: 'System.String Note'
         Type: 'System.String'  Value: 'This is a note on the class.'
         MemberInfo: 'Int32[] Numbers'
         Array of 'System.Int32[]':
             Type: 'System.Int32'  Value: '53'
             Type: 'System.Int32'  Value: '57'
             Type: 'System.Int32'  Value: '59'

Attributes for member: 'Void TestMethod(System.Object)'
   [ExampleAttribute(Note = "This is a note on a method.")]
      Constructor: 'Void .ctor()'
      Constructor arguments:
      Named arguments:
         MemberInfo: 'System.String Note'
         Type: 'System.String'  Value: 'This is a note on a method.'

Attributes for parameter: 'System.Object arg'
   [ExampleAttribute()]
      Constructor: 'Void .ctor()'
      Constructor arguments:
      Named arguments:
*/

Plataforma universal de Windows
Disponible desde 8
.NET Framework
Disponible desde 2.0
Biblioteca de clases portable
Se admite en: plataformas portátiles de .NET
Windows Phone Silverlight
Disponible desde 8.0
Windows Phone
Disponible desde 8.1

Cualquier miembro ( Compartido en Visual Basic) estático público de este tipo es seguro para subprocesos. No se garantiza que los miembros de instancia sean seguros para subprocesos.

Volver al principio
Mostrar: