Lire en anglais

Partager via


CustomAttributeData Classe

Définition

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.

C#
public class CustomAttributeData
C#
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public sealed class CustomAttributeData
C#
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class CustomAttributeData
Héritage
CustomAttributeData
Attributs

Exemples

L’exemple suivant définit un attribut personnalisé avec quatre constructeurs et quatre propriétés. Deux des propriétés sont en lecture seule et sont définies à l’aide des paramètres positionnels des constructeurs. Les deux autres propriétés sont en lecture/écriture et ne peuvent être définies qu’à l’aide d’arguments nommés. Une propriété positionnelle est un tableau de chaînes, et une propriété nommée est un tableau d’entiers.

L’attribut est appliqué à l’assembly, à un type déclaré dans l’assembly, à une méthode du type, et à un paramètre de la méthode. Différents constructeurs sont utilisés pour ces cas. Lorsqu’il est exécuté, l’assembly se charge lui-même dans le contexte de réflexion uniquement et affiche des informations sur les attributs personnalisés qui lui ont été appliqués, ainsi que sur le type et les membres qu’il contient.

L’attribut appliqué au type illustre les propriétés du tableau, avec des arguments positionnels et nommés.

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

Remarques

Le code en cours d’examen dans le contexte de réflexion uniquement ne peut pas être exécuté. Il n’est donc pas toujours possible d’examiner les attributs personnalisés en créant des instances de ceux-ci, puis en examinant leurs propriétés, à l’aide de méthodes telles que Attribute.GetCustomAttributes, MemberInfo.GetCustomAttributes, et ainsi de suite. Si le code du type d’attribut lui-même est chargé dans le contexte de réflexion uniquement, il ne peut pas être exécuté.

La CustomAttributeData classe permet l’examen des attributs personnalisés dans le contexte de réflexion uniquement en fournissant une abstraction pour les attributs. Les membres de cette classe peuvent être utilisés pour obtenir les arguments positionnels et les arguments nommés de l’attribut. Utilisez la ConstructorArguments propriété pour obtenir une liste de CustomAttributeTypedArgument structures qui représentent les arguments positionnels, et utilisez la NamedArguments propriété pour obtenir une liste de CustomAttributeNamedArgument structures qui représentent les arguments nommés.

Notes

La CustomAttributeNamedArgument structure fournit uniquement des informations sur la propriété d’attribut utilisée pour obtenir et définir la valeur de l’argument. Pour obtenir le type et la valeur de l’argument, utilisez la CustomAttributeNamedArgument.TypedValue propriété pour obtenir une CustomAttributeTypedArgument structure.

Lorsque vous avez une CustomAttributeTypedArgument structure pour un argument, qu’il soit nommé ou positionnel, utilisez la CustomAttributeTypedArgument.ArgumentType propriété pour obtenir le type et la CustomAttributeTypedArgument.Value propriété pour obtenir la valeur.

Notes

Pour un argument de tableau, la CustomAttributeTypedArgument.Value propriété retourne un générique ReadOnlyCollection<T> d’objets CustomAttributeTypedArgument . Chaque CustomAttributeTypedArgument objet de la collection représente l’élément correspondant du tableau.

CustomAttributeData peut être utilisé dans le contexte d’exécution ainsi que dans le contexte de réflexion uniquement. Par exemple, vous pouvez éviter de charger l’assembly qui contient le code d’un attribut personnalisé. L’utilisation de la CustomAttributeData classe diffère de l’utilisation de méthodes telles que Attribute.GetCustomAttributes:

  • Les propriétés et méthodes de CustomAttributeData fournissent uniquement les valeurs qui ont été spécifiées pour l’attribut instance, et non la sémantique du constructeur. Par exemple, un argument de chaîne d’un attribut peut être converti en interne en une autre représentation et retourné sous une forme canonique ; ou une propriété peut avoir des effets secondaires lorsque le code d’attribut réel est exécuté.

  • Les propriétés et méthodes de ne vous permettent pas de CustomAttributeData récupérer les attributs personnalisés hérités des classes de base.

Pour créer des instances de la CustomAttributeData classe, utilisez les static méthodes de fabrique (Shared en Visual Basic). GetCustomAttributes

Constructeurs

CustomAttributeData()

Initialise une nouvelle instance de la classe CustomAttributeData.

Propriétés

AttributeType

Obtient le type de l'attribut.

Constructor

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

ConstructorArguments

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

NamedArguments

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

Méthodes

Equals(Object)

Retourne une valeur qui indique si cette instance est égale à un objet spécifié.

Equals(Object)

Détermine si l'objet spécifié est égal à l'objet actuel.

(Hérité de Object)
GetCustomAttributes(Assembly)

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

GetCustomAttributes(MemberInfo)

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

GetCustomAttributes(Module)

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

GetCustomAttributes(ParameterInfo)

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

GetHashCode()

Sert de fonction de hachage pour un type particulier.

GetHashCode()

Fait office de fonction de hachage par défaut.

(Hérité de Object)
GetType()

Obtient le Type de l'instance actuelle.

(Hérité de Object)
MemberwiseClone()

Crée une copie superficielle du Object actuel.

(Hérité de Object)
ToString()

Retourne une représentation sous forme de chaîne de l'attribut personnalisé.

ToString()

Retourne une chaîne qui représente l'objet actuel.

(Hérité de Object)

S’applique à

Produit Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Voir aussi