Leggi in inglese

Condividi tramite


CustomAttributeData Classe

Definizione

Fornisce l'accesso ai dati degli attributi personalizzati per gli assembly, i moduli, i tipi, i membri e i parametri che vengono caricati nel contesto ReflectionOnly.

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
Ereditarietà
CustomAttributeData
Attributi

Esempio

Nell'esempio seguente viene definito un attributo personalizzato con quattro costruttori e quattro proprietà. Due delle proprietà sono di sola lettura e vengono impostati usando i parametri posizionali dei costruttori. Le altre due proprietà sono di lettura/scrittura e possono essere impostate solo usando argomenti denominati. Una proprietà posizionale è una matrice di stringhe e una proprietà denominata è una matrice di interi.

L'attributo è applicato all'assembly, a un tipo dichiarato nell'assembly, a un metodo del tipo e a un parametro del metodo. Per questi casi vengono usati diversi costruttori. Quando viene eseguito, l'assembly si carica nel contesto di sola reflection e visualizza le informazioni sugli attributi personalizzati applicati a esso e al tipo e ai membri che contiene.

L'attributo applicato al tipo illustra le proprietà della matrice, con argomenti posizionati e denominati.

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

Commenti

Il codice esaminato nel contesto di solo reflection non può essere eseguito, quindi non è sempre possibile esaminare gli attributi personalizzati creando istanze di essi e quindi esaminando le proprietà, usando metodi come Attribute.GetCustomAttributes, MemberInfo.GetCustomAttributese così via. Se il codice per il tipo di attributo stesso viene caricato nel contesto di sola reflection, non può essere eseguito.

La CustomAttributeData classe consente l'esame degli attributi personalizzati nel contesto di sola reflection fornendo un'astrazione per gli attributi. I membri di questa classe possono essere usati per ottenere gli argomenti posizionali e gli argomenti denominati dell'attributo. Utilizzare la proprietà per ottenere un elenco di strutture che rappresentano gli argomenti posizionali e usare la ConstructorArgumentsNamedArguments proprietà per ottenere un elenco di CustomAttributeTypedArgumentCustomAttributeNamedArgument strutture che rappresentano gli argomenti denominati.

Nota

La CustomAttributeNamedArgument struttura fornisce solo informazioni sulla proprietà dell'attributo utilizzata per ottenere e impostare il valore dell'argomento. Per ottenere il tipo e il valore dell'argomento, utilizzare la CustomAttributeNamedArgument.TypedValue proprietà per ottenere una CustomAttributeTypedArgument struttura.

Quando si dispone di una struttura per un CustomAttributeTypedArgument argomento, ovvero denominata o posizionale, utilizzare la CustomAttributeTypedArgument.ArgumentType proprietà per ottenere il tipo e la CustomAttributeTypedArgument.Value proprietà per ottenere il valore.

Nota

Per un argomento matrice, la CustomAttributeTypedArgument.Value proprietà restituisce un generico ReadOnlyCollection<T> di CustomAttributeTypedArgument oggetti. Ogni CustomAttributeTypedArgument oggetto nell'insieme rappresenta l'elemento corrispondente della matrice.

CustomAttributeData può essere usato nel contesto di esecuzione e nel contesto di sola reflection. Ad esempio, è possibile evitare di caricare l'assembly contenente il codice per un attributo personalizzato. L'uso della classe è diverso dall'uso CustomAttributeData di metodi come Attribute.GetCustomAttributes:

  • Le proprietà e i metodi di CustomAttributeData forniscono solo i valori specificati per l'istanza dell'attributo, non la semantica del costruttore. Ad esempio, un argomento stringa di un attributo potrebbe essere convertito internamente in un'altra rappresentazione e restituito in una forma canonica; o una proprietà potrebbe avere effetti collaterali quando viene eseguito il codice di attributo effettivo.

  • Le proprietà e i metodi di CustomAttributeData non consentono di recuperare gli attributi personalizzati ereditati dalle classi di base.

Per creare istanze della CustomAttributeData classe, usare i static metodi di factory (Shared in Visual Basic). GetCustomAttributes

Costruttori

CustomAttributeData()

Inizializza una nuova istanza della classe CustomAttributeData.

Proprietà

AttributeType

Ottiene il tipo di attributo.

Constructor

Ottiene un oggetto ConstructorInfo che rappresenta il costruttore che avrebbe inizializzato l'attributo personalizzato.

ConstructorArguments

Ottiene l'elenco degli argomenti posizionali specificati per l'istanza dell'attributo rappresentata dall'oggetto CustomAttributeData.

NamedArguments

Ottiene l'elenco degli argomenti denominati specificati per l'istanza dell'attributo rappresentata dall'oggetto CustomAttributeData.

Metodi

Equals(Object)

Restituisce un valore che indica se questa istanza è uguale a un oggetto specificato.

Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
GetCustomAttributes(Assembly)

Restituisce un elenco di oggetti CustomAttributeData che rappresentano i dati relativi agli attributi applicati all'assembly di destinazione.

GetCustomAttributes(MemberInfo)

Restituisce un elenco di oggetti CustomAttributeData che rappresentano i dati relativi agli attributi applicati al membro di destinazione.

GetCustomAttributes(Module)

Restituisce un elenco di oggetti CustomAttributeData che rappresentano i dati relativi agli attributi applicati al modulo di destinazione.

GetCustomAttributes(ParameterInfo)

Restituisce un elenco di oggetti CustomAttributeData che rappresentano i dati relativi agli attributi applicati al parametro di destinazione.

GetHashCode()

Svolge una funzione hash per un tipo particolare.

GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetType()

Ottiene l'oggetto Type dell'istanza corrente.

(Ereditato da Object)
MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
ToString()

Restituisce una rappresentazione in formato stringa dell'attributo personalizzato.

ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)

Si applica a

Prodotto Versioni
.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

Vedi anche