Cet article a fait l’objet d’une traduction automatique. Pour afficher l’article en anglais, activez la case d’option Anglais. Vous pouvez également afficher le texte anglais dans une fenêtre contextuelle en faisant glisser le pointeur de la souris sur le texte traduit.
Traduction
Anglais

CustomAttributeData classe

 

Date de publication : novembre 2016

Fournit un accès aux données d'attribut personnalisé pour les assemblys, les modules, les types, les membres et les paramètres qui sont chargés dans le contexte de réflexion uniquement.

Espace de noms:   System.Reflection
Assembly:  mscorlib (dans mscorlib.dll)

System.Object
  System.Reflection.CustomAttributeData

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

NomDescription
System_CAPS_protmethodCustomAttributeData()

Initialise une nouvelle instance de la classe CustomAttributeData.

NomDescription
System_CAPS_pubpropertyAttributeType

Obtient le type de l’attribut.

System_CAPS_pubpropertyConstructor

Obtient un objet ConstructorInfo qui représente le constructeur qui aurait initialisé l’attribut personnalisé.

System_CAPS_pubpropertyConstructorArguments

Obtient la liste des arguments de position spécifiés pour l’instance d’attribut représenté par le CustomAttributeData objet.

System_CAPS_pubpropertyNamedArguments

Obtient la liste des arguments nommés spécifiés pour l’instance d’attribut représenté par le CustomAttributeData objet.

NomDescription
System_CAPS_pubmethodEquals(Object)

Retourne une valeur qui indique si cette instance est égale à un objet spécifié.(Remplace Object.Equals(Object).)

System_CAPS_protmethodFinalize()

Autorise un objet à tenter de libérer des ressources et d'exécuter d'autres opérations de nettoyage avant qu'il ne soit récupéré par l'opération garbage collection. (Hérité de Object.)

System_CAPS_pubmethodSystem_CAPS_staticGetCustomAttributes(Assembly)

Renvoie une liste d’objets CustomAttributeData représentant des données sur les attributs qui ont été appliqués à l’assembly cible.

System_CAPS_pubmethodSystem_CAPS_staticGetCustomAttributes(MemberInfo)

Renvoie une liste d’objets CustomAttributeData représentant des données sur les attributs qui ont été appliqués au membre cible.

System_CAPS_pubmethodSystem_CAPS_staticGetCustomAttributes(Module)

Renvoie une liste d’objets CustomAttributeData représentant des données sur les attributs qui ont été appliqués au module cible.

System_CAPS_pubmethodSystem_CAPS_staticGetCustomAttributes(ParameterInfo)

Retourne une liste d’objets CustomAttributeData représentant des données sur les attributs qui ont été appliqués au paramètre cible.

System_CAPS_pubmethodGetHashCode()

Sert de fonction de hachage pour un type particulier.(Remplace Object.GetHashCode().)

System_CAPS_pubmethodGetType()

Obtient le Type de l'instance actuelle.(Hérité de Object.)

System_CAPS_protmethodMemberwiseClone()

Crée une copie superficielle du Object actuel.(Hérité de Object.)

System_CAPS_pubmethodToString()

Retourne une représentation sous forme de chaîne de l’attribut personnalisé.(Remplace 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_noteRemarque

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_noteRemarque

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:
*/

Plateforme Windows universelle
Disponible depuis 8
.NET Framework
Disponible depuis 2.0
Bibliothèque de classes portable
Pris en charge dans : plateformes .NET portables
Silverlight pour Windows Phone
Disponible depuis 8.0
Windows Phone
Disponible depuis 8.1

Tous les membres statiques publics ( Shared en Visual Basic) de ce type sont thread-safe. Les membres d’instance n’ont pas la garantie d’être thread-safe.

Retour au début
Afficher: