Condividi tramite


Attribute Classe

Definizione

Rappresenta la classe base per gli attributi personalizzati.

public ref class Attribute abstract
public ref class Attribute abstract : System::Runtime::InteropServices::_Attribute
[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple=false, Inherited=true)]
public abstract class Attribute
[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple=false, Inherited=true)]
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
[System.Serializable]
public abstract class Attribute : System.Runtime.InteropServices._Attribute
[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple=false, Inherited=true)]
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class Attribute : System.Runtime.InteropServices._Attribute
[<System.AttributeUsage(System.AttributeTargets.All, AllowMultiple=false, Inherited=true)>]
type Attribute = class
[<System.AttributeUsage(System.AttributeTargets.All, AllowMultiple=false, Inherited=true)>]
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)>]
[<System.Serializable>]
type Attribute = class
    interface _Attribute
[<System.AttributeUsage(System.AttributeTargets.All, AllowMultiple=false, Inherited=true)>]
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)>]
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type Attribute = class
    interface _Attribute
Public MustInherit Class Attribute
Public MustInherit Class Attribute
Implements _Attribute
Ereditarietà
Attribute
Derivato
Attributi
Implementazioni

Esempio

Nell'esempio di codice seguente viene illustrato l'utilizzo di Attribute.

using namespace System;
using namespace System::Reflection;

// An enumeration of animals. Start at 1 (0 = uninitialized).
public enum class Animal
{
    // Pets.
    Dog = 1,
    Cat, Bird
};

// A custom attribute to allow a target to have a pet.
public ref class AnimalTypeAttribute: public Attribute
{
public:

    // The constructor is called when the attribute is set.
    AnimalTypeAttribute( Animal pet )
    {
        thePet = pet;
    }


protected:

    // Keep a variable internally ...
    Animal thePet;

public:

    property Animal Pet 
    {
        // .. and show a copy to the outside world.
        Animal get()
        {
            return thePet;
        }

        void set( Animal value )
        {
            thePet = value;
        }
    }
};

// A test class where each method has its own pet.
ref class AnimalTypeTestClass
{
public:

    [AnimalType(Animal::Dog)]
    void DogMethod(){}


    [AnimalType(Animal::Cat)]
    void CatMethod(){}

    [AnimalType(Animal::Bird)]
    void BirdMethod(){}

};

int main()
{
    AnimalTypeTestClass^ testClass = gcnew AnimalTypeTestClass;
    Type^ type = testClass->GetType();

    // Iterate through all the methods of the class.
    System::Collections::IEnumerator^ myEnum = 
        type->GetMethods()->GetEnumerator();
    while ( myEnum->MoveNext() )
    {
        MethodInfo^ mInfo = safe_cast<MethodInfo^>(myEnum->Current);

        // Iterate through all the Attributes for each method.
        System::Collections::IEnumerator^ myEnum1 = 
            Attribute::GetCustomAttributes( mInfo )->GetEnumerator();
        while ( myEnum1->MoveNext() )
        {
            Attribute^ attr = safe_cast<Attribute^>(myEnum1->Current);

            // Check for the AnimalType attribute.
            if ( attr->GetType() == AnimalTypeAttribute::typeid )
                Console::WriteLine( "Method {0} has a pet {1} attribute.", 
                mInfo->Name, (dynamic_cast<AnimalTypeAttribute^>(attr))->Pet );
        }
    }
}

/*
 * Output:
 * Method DogMethod has a pet Dog attribute.
 * Method CatMethod has a pet Cat attribute.
 * Method BirdMethod has a pet Bird attribute.
 */
using System;
using System.Reflection;

// An enumeration of animals. Start at 1 (0 = uninitialized).
public enum Animal {
    // Pets.
    Dog = 1,
    Cat,
    Bird,
}

// A custom attribute to allow a target to have a pet.
public class AnimalTypeAttribute : Attribute {
    // The constructor is called when the attribute is set.
    public AnimalTypeAttribute(Animal pet) {
        thePet = pet;
    }

    // Keep a variable internally ...
    protected Animal thePet;

    // .. and show a copy to the outside world.
    public Animal Pet {
        get { return thePet; }
        set { thePet = value; }
    }
}

// A test class where each method has its own pet.
class AnimalTypeTestClass {
    [AnimalType(Animal.Dog)]
    public void DogMethod() {}

    [AnimalType(Animal.Cat)]
    public void CatMethod() {}

    [AnimalType(Animal.Bird)]
    public void BirdMethod() {}
}

class DemoClass {
    static void Main(string[] args) {
        AnimalTypeTestClass testClass = new AnimalTypeTestClass();
        Type type = testClass.GetType();
        // Iterate through all the methods of the class.
        foreach(MethodInfo mInfo in type.GetMethods()) {
            // Iterate through all the Attributes for each method.
            foreach (Attribute attr in
                Attribute.GetCustomAttributes(mInfo)) {
                // Check for the AnimalType attribute.
                if (attr.GetType() == typeof(AnimalTypeAttribute))
                    Console.WriteLine(
                        "Method {0} has a pet {1} attribute.",
                        mInfo.Name, ((AnimalTypeAttribute)attr).Pet);
            }
        }
    }
}
/*
 * Output:
 * Method DogMethod has a pet Dog attribute.
 * Method CatMethod has a pet Cat attribute.
 * Method BirdMethod has a pet Bird attribute.
 */
open System

// An enumeration of animals. Start at 1 (0 = uninitialized).
type Animal =
    | Dog = 1
    | Cat = 2
    | Bird = 3

// A custom attribute to allow a target to have a pet.
type AnimalTypeAttribute(pet) =
    inherit Attribute()
    member val Pet = pet with get, set

// A test class where each method has its own pet.
type AnimalTypeTestClass() =
    [<AnimalType(Animal.Dog)>]
    member _.DogMethod() = ()

    [<AnimalType(Animal.Cat)>]
    member _.CatMethod() = ()

    [<AnimalType(Animal.Bird)>]
    member _.BirdMethod() = ()

let testClass = AnimalTypeTestClass()
let clsType = testClass.GetType()
// Iterate through all the methods of the class.
for mInfo in clsType.GetMethods() do
    // Iterate through all the Attributes for each method.
    for attr in Attribute.GetCustomAttributes mInfo do
        // Check for the AnimalType attribute.
        if attr.GetType() = typeof<AnimalTypeAttribute> then
            printfn $"Method {mInfo.Name} has a pet {(attr :?> AnimalTypeAttribute).Pet} attribute."

// Output:
//   Method DogMethod has a pet Dog attribute.
//   Method CatMethod has a pet Cat attribute.
//   Method BirdMethod has a pet Bird attribute.
Imports System.Reflection

Public Module CustomAttrVB

    ' An enumeration of animals. Start at 1 (0 = uninitialized).
    Public Enum Animal
        ' Pets
        Dog = 1
        Cat
        Bird
    End Enum

    ' Visual Basic requires the AttributeUsage be specified.
    ' A custom attribute to allow a target to have a pet.
    <AttributeUsage(AttributeTargets.Method)> _
    Public Class AnimalTypeAttribute
        Inherits Attribute

        ' The constructor is called when the attribute is set.
        Public Sub New(ByVal animal As Animal)
            Me.thePet = animal
        End Sub

        ' Keep a variable internally ...
        Protected thePet As Animal

        ' .. and show a copy to the outside world.
        Public Property Pet() As Animal
            Get
                Return thePet
            End Get
            Set(ByVal Value As Animal)
                thePet = Value
            End Set
        End Property

    End Class

    ' A test class where each method has its own pet.
    Class AnimalTypeTestClass

        <AnimalType(Animal.Dog)> _
        Public Sub DogMethod()
        End Sub

        <AnimalType(Animal.Cat)> _
        Public Sub CatMethod()
        End Sub

        <AnimalType(Animal.Bird)> _
        Public Sub BirdMethod()
        End Sub
    End Class

    ' The runtime test.
    Sub Main()
        Dim testClass As New AnimalTypeTestClass()
        Dim tcType As Type = testClass.GetType()
        Dim mInfo As MethodInfo
        ' Iterate through all the methods of the class.
        For Each mInfo In tcType.GetMethods()
            Dim attr As Attribute
            ' Iterate through all the attributes of the method.
            For Each attr In Attribute.GetCustomAttributes(mInfo)
                If TypeOf attr Is AnimalTypeAttribute Then
                    Dim attrCustom As AnimalTypeAttribute = _
                        CType(attr, AnimalTypeAttribute)
                    Console.WriteLine("Method {0} has a pet {1} attribute.", _
                         mInfo.Name(), attrCustom.Pet.ToString())
                End If
            Next
        Next
    End Sub
End Module

' Output:
' Method DogMethod has a pet Dog attribute.
' Method CatMethod has a pet Cat attribute.
' Method BirdMethod has a pet Bird attribute.

Commenti

La classe Attribute associa informazioni di sistema predefinite o informazioni personalizzate definite dall'utente a un elemento di destinazione. Un elemento di destinazione può essere un assembly, una classe, un costruttore, un delegato, un evento, un campo, un'interfaccia, un metodo, un modulo di file eseguibile portabile, un parametro, una proprietà, un valore restituito, uno struct o un altro attributo.

Le informazioni fornite da un attributo sono note anche come metadati. I metadati possono essere esaminati in fase di esecuzione dall'applicazione per controllare il modo in cui il programma elabora i dati o prima della fase di esecuzione da strumenti esterni per controllare il modo in cui l'applicazione stessa viene elaborata o gestita. Ad esempio, .NET predefinito e usa tipi di attributo per controllare il comportamento di runtime e alcuni linguaggi di programmazione usano tipi di attributo per rappresentare le funzionalità del linguaggio non supportate direttamente dal sistema di tipi comuni .NET.

Tutti i tipi di attributo derivano direttamente o indirettamente dalla classe Attribute. Gli attributi possono essere applicati a qualsiasi elemento di destinazione; più attributi possono essere applicati allo stesso elemento di destinazione; Gli attributi e possono essere ereditati da un elemento derivato da un elemento di destinazione. Usare la classe AttributeTargets per specificare l'elemento di destinazione a cui viene applicato l'attributo.

La classe Attribute fornisce metodi pratici per recuperare e testare attributi personalizzati. Per altre informazioni sull'uso degli attributi, vedere 'applicazione di attributi e attributi .

Costruttori

Attribute()

Inizializza una nuova istanza della classe Attribute.

Proprietà

TypeId

Se implementato in una classe derivata, ottiene un identificatore univoco per questo Attribute.

Metodi

Equals(Object)

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

GetCustomAttribute(Assembly, Type)

Recupera un attributo personalizzato applicato a un assembly specificato. I parametri specificano l'assembly e il tipo dell'attributo personalizzato da cercare.

GetCustomAttribute(Assembly, Type, Boolean)

Recupera un attributo personalizzato applicato a un assembly. I parametri specificano l'assembly, il tipo dell'attributo personalizzato da cercare e un'opzione di ricerca ignorata.

GetCustomAttribute(MemberInfo, Type)

Recupera un attributo personalizzato applicato a un membro di un tipo. I parametri specificano il membro e il tipo dell'attributo personalizzato da cercare.

GetCustomAttribute(MemberInfo, Type, Boolean)

Recupera un attributo personalizzato applicato a un membro di un tipo. I parametri specificano il membro, il tipo dell'attributo personalizzato da cercare e se cercare i predecessori del membro.

GetCustomAttribute(Module, Type)

Recupera un attributo personalizzato applicato a un modulo. I parametri specificano il modulo e il tipo dell'attributo personalizzato da cercare.

GetCustomAttribute(Module, Type, Boolean)

Recupera un attributo personalizzato applicato a un modulo. I parametri specificano il modulo, il tipo dell'attributo personalizzato da cercare e un'opzione di ricerca ignorata.

GetCustomAttribute(ParameterInfo, Type)

Recupera un attributo personalizzato applicato a un parametro del metodo. I parametri specificano il parametro del metodo e il tipo dell'attributo personalizzato da cercare.

GetCustomAttribute(ParameterInfo, Type, Boolean)

Recupera un attributo personalizzato applicato a un parametro del metodo. I parametri specificano il parametro del metodo, il tipo dell'attributo personalizzato da cercare e se cercare i predecessori del parametro del metodo.

GetCustomAttributes(Assembly)

Recupera una matrice degli attributi personalizzati applicati a un assembly. Un parametro specifica l'assembly.

GetCustomAttributes(Assembly, Boolean)

Recupera una matrice degli attributi personalizzati applicati a un assembly. I parametri specificano l'assembly e un'opzione di ricerca ignorata.

GetCustomAttributes(Assembly, Type)

Recupera una matrice degli attributi personalizzati applicati a un assembly. I parametri specificano l'assembly e il tipo dell'attributo personalizzato da cercare.

GetCustomAttributes(Assembly, Type, Boolean)

Recupera una matrice degli attributi personalizzati applicati a un assembly. I parametri specificano l'assembly, il tipo dell'attributo personalizzato da cercare e un'opzione di ricerca ignorata.

GetCustomAttributes(MemberInfo)

Recupera una matrice degli attributi personalizzati applicati a un membro di un tipo. Un parametro specifica il membro.

GetCustomAttributes(MemberInfo, Boolean)

Recupera una matrice degli attributi personalizzati applicati a un membro di un tipo. I parametri specificano il membro, il tipo dell'attributo personalizzato da cercare e se cercare i predecessori del membro.

GetCustomAttributes(MemberInfo, Type)

Recupera una matrice degli attributi personalizzati applicati a un membro di un tipo. I parametri specificano il membro e il tipo dell'attributo personalizzato da cercare.

GetCustomAttributes(MemberInfo, Type, Boolean)

Recupera una matrice degli attributi personalizzati applicati a un membro di un tipo. I parametri specificano il membro, il tipo dell'attributo personalizzato da cercare e se cercare i predecessori del membro.

GetCustomAttributes(Module)

Recupera una matrice degli attributi personalizzati applicati a un modulo. Un parametro specifica il modulo.

GetCustomAttributes(Module, Boolean)

Recupera una matrice degli attributi personalizzati applicati a un modulo. I parametri specificano il modulo e un'opzione di ricerca ignorata.

GetCustomAttributes(Module, Type)

Recupera una matrice degli attributi personalizzati applicati a un modulo. I parametri specificano il modulo e il tipo dell'attributo personalizzato da cercare.

GetCustomAttributes(Module, Type, Boolean)

Recupera una matrice degli attributi personalizzati applicati a un modulo. I parametri specificano il modulo, il tipo dell'attributo personalizzato da cercare e un'opzione di ricerca ignorata.

GetCustomAttributes(ParameterInfo)

Recupera una matrice degli attributi personalizzati applicati a un parametro del metodo. Un parametro specifica il parametro del metodo.

GetCustomAttributes(ParameterInfo, Boolean)

Recupera una matrice degli attributi personalizzati applicati a un parametro del metodo. I parametri specificano il parametro del metodo e se cercare i predecessori del parametro del metodo.

GetCustomAttributes(ParameterInfo, Type)

Recupera una matrice degli attributi personalizzati applicati a un parametro del metodo. I parametri specificano il parametro del metodo e il tipo dell'attributo personalizzato da cercare.

GetCustomAttributes(ParameterInfo, Type, Boolean)

Recupera una matrice degli attributi personalizzati applicati a un parametro del metodo. I parametri specificano il parametro del metodo, il tipo dell'attributo personalizzato da cercare e se cercare i predecessori del parametro del metodo.

GetHashCode()

Restituisce il codice hash per questa istanza.

GetType()

Ottiene il Type dell'istanza corrente.

(Ereditato da Object)
IsDefaultAttribute()

Quando sottoposto a override in una classe derivata, indica se il valore di questa istanza è il valore predefinito per la classe derivata.

IsDefined(Assembly, Type)

Determina se gli attributi personalizzati vengono applicati a un assembly. I parametri specificano l'assembly e il tipo dell'attributo personalizzato da cercare.

IsDefined(Assembly, Type, Boolean)

Determina se gli attributi personalizzati vengono applicati a un assembly. I parametri specificano l'assembly, il tipo dell'attributo personalizzato da cercare e un'opzione di ricerca ignorata.

IsDefined(MemberInfo, Type)

Determina se gli attributi personalizzati vengono applicati a un membro di un tipo. I parametri specificano il membro e il tipo dell'attributo personalizzato da cercare.

IsDefined(MemberInfo, Type, Boolean)

Determina se gli attributi personalizzati vengono applicati a un membro di un tipo. I parametri specificano il membro, il tipo dell'attributo personalizzato da cercare e se cercare i predecessori del membro.

IsDefined(Module, Type)

Determina se a un modulo vengono applicati attributi personalizzati di un tipo specificato. I parametri specificano il modulo e il tipo dell'attributo personalizzato da cercare.

IsDefined(Module, Type, Boolean)

Determina se a un modulo vengono applicati attributi personalizzati. I parametri specificano il modulo, il tipo dell'attributo personalizzato da cercare e un'opzione di ricerca ignorata.

IsDefined(ParameterInfo, Type)

Determina se gli attributi personalizzati vengono applicati a un parametro del metodo. I parametri specificano il parametro del metodo e il tipo dell'attributo personalizzato da cercare.

IsDefined(ParameterInfo, Type, Boolean)

Determina se gli attributi personalizzati vengono applicati a un parametro del metodo. I parametri specificano il parametro del metodo, il tipo dell'attributo personalizzato da cercare e se cercare i predecessori del parametro del metodo.

Match(Object)

Quando sottoposto a override in una classe derivata, restituisce un valore che indica se questa istanza è uguale a un oggetto specificato.

MemberwiseClone()

Crea una copia superficiale del Objectcorrente.

(Ereditato da Object)
ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)

Implementazioni dell'interfaccia esplicita

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Esegue il mapping di un set di nomi a un set corrispondente di identificatori dispatch.

_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera le informazioni sul tipo per un oggetto, che può essere utilizzato per ottenere le informazioni sul tipo per un'interfaccia.

_Attribute.GetTypeInfoCount(UInt32)

Recupera il numero di interfacce di informazioni sul tipo fornite da un oggetto (0 o 1).

_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fornisce l'accesso alle proprietà e ai metodi esposti da un oggetto .

Si applica a

Thread safety

Questo tipo è thread-safe.

Vedi anche