Attribute Klasa

Definicja

Reprezentuje klasę bazową dla atrybutów niestandardowych.

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
Dziedziczenie
Attribute
Pochodne
Atrybuty
Implementuje

Przykłady

W poniższym przykładzie kodu pokazano użycie obiektu 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.

Uwagi

Klasa Attribute kojarzy wstępnie zdefiniowane informacje systemowe lub informacje niestandardowe zdefiniowane przez użytkownika z elementem docelowym. Elementem docelowym może być zestaw, klasa, konstruktor, delegat, wyliczenie, zdarzenie, pole, interfejs, metoda, przenośny moduł pliku wykonywalnego, parametr, właściwość, wartość zwracana, struktura lub inny atrybut.

Informacje udostępniane przez atrybut są również nazywane metadanymi. Metadane można zbadać w czasie wykonywania przez aplikację, aby kontrolować sposób przetwarzania danych przez program lub przed uruchomieniem przez narzędzia zewnętrzne w celu kontrolowania sposobu przetwarzania lub konserwacji aplikacji. Na przykład program .NET wstępnie zdefiniowane i używa typów atrybutów do kontrolowania zachowania w czasie wykonywania, a niektóre języki programowania używają typów atrybutów do reprezentowania funkcji językowych nieobsługiwanych bezpośrednio przez system typowego typu platformy .NET.

Wszystkie typy atrybutów pochodzą bezpośrednio lub pośrednio z Attribute klasy. Atrybuty można zastosować do dowolnego elementu docelowego; do tego samego elementu docelowego można zastosować wiele atrybutów; atrybuty i mogą być dziedziczone przez element pochodzący z elementu docelowego. AttributeTargets Użyj klasy, aby określić element docelowy, do którego zastosowano atrybut.

Klasa Attribute zapewnia wygodne metody pobierania i testowania atrybutów niestandardowych. Aby uzyskać więcej informacji na temat używania atrybutów, zobacz Stosowanie atrybutów i atrybutów.

Konstruktory

Attribute()

Inicjuje nowe wystąpienie klasy Attribute.

Właściwości

TypeId

Po zaimplementowaniu w klasie pochodnej pobiera unikatowy identyfikator dla tego elementu Attribute.

Metody

Equals(Object)

Zwraca wartość wskazującą, czy to wystąpienie jest równe podanemu obiektowi.

GetCustomAttribute(Assembly, Type)

Pobiera atrybut niestandardowy zastosowany do określonego zestawu. Parametry określają zestaw i typ atrybutu niestandardowego do wyszukania.

GetCustomAttribute(Assembly, Type, Boolean)

Pobiera atrybut niestandardowy zastosowany do zestawu. Parametry określają zestaw, typ atrybutu niestandardowego do wyszukania i ignorowaną opcję wyszukiwania.

GetCustomAttribute(MemberInfo, Type)

Pobiera atrybut niestandardowy zastosowany do elementu członkowskiego typu. Parametry określają element członkowski i typ atrybutu niestandardowego do wyszukania.

GetCustomAttribute(MemberInfo, Type, Boolean)

Pobiera atrybut niestandardowy zastosowany do elementu członkowskiego typu. Parametry określają element członkowski, typ atrybutu niestandardowego do wyszukania i czy wyszukiwać elementy członkowskie.

GetCustomAttribute(Module, Type)

Pobiera atrybut niestandardowy zastosowany do modułu. Parametry określają moduł i typ atrybutu niestandardowego do wyszukania.

GetCustomAttribute(Module, Type, Boolean)

Pobiera atrybut niestandardowy zastosowany do modułu. Parametry określają moduł, typ atrybutu niestandardowego do wyszukania i ignorowaną opcję wyszukiwania.

GetCustomAttribute(ParameterInfo, Type)

Pobiera atrybut niestandardowy zastosowany do parametru metody. Parametry określają parametr metody i typ atrybutu niestandardowego do wyszukania.

GetCustomAttribute(ParameterInfo, Type, Boolean)

Pobiera atrybut niestandardowy zastosowany do parametru metody. Parametry określają parametr metody, typ atrybutu niestandardowego do wyszukania i czy wyszukiwać elementy podrzędne parametru metody.

GetCustomAttributes(Assembly)

Pobiera tablicę atrybutów niestandardowych zastosowanych do zestawu. Parametr określa zestaw.

GetCustomAttributes(Assembly, Boolean)

Pobiera tablicę atrybutów niestandardowych zastosowanych do zestawu. Parametry określają zestaw i ignorowaną opcję wyszukiwania.

GetCustomAttributes(Assembly, Type)

Pobiera tablicę atrybutów niestandardowych zastosowanych do zestawu. Parametry określają zestaw i typ atrybutu niestandardowego do wyszukania.

GetCustomAttributes(Assembly, Type, Boolean)

Pobiera tablicę atrybutów niestandardowych zastosowanych do zestawu. Parametry określają zestaw, typ atrybutu niestandardowego do wyszukania i ignorowaną opcję wyszukiwania.

GetCustomAttributes(MemberInfo)

Pobiera tablicę atrybutów niestandardowych zastosowanych do elementu członkowskiego typu. Parametr określa element członkowski.

GetCustomAttributes(MemberInfo, Boolean)

Pobiera tablicę atrybutów niestandardowych zastosowanych do elementu członkowskiego typu. Parametry określają element członkowski, typ atrybutu niestandardowego do wyszukania i czy wyszukiwać elementy członkowskie.

GetCustomAttributes(MemberInfo, Type)

Pobiera tablicę atrybutów niestandardowych zastosowanych do elementu członkowskiego typu. Parametry określają element członkowski i typ atrybutu niestandardowego do wyszukania.

GetCustomAttributes(MemberInfo, Type, Boolean)

Pobiera tablicę atrybutów niestandardowych zastosowanych do elementu członkowskiego typu. Parametry określają element członkowski, typ atrybutu niestandardowego do wyszukania i czy wyszukiwać elementów podrzędnych elementu członkowskiego.

GetCustomAttributes(Module)

Pobiera tablicę atrybutów niestandardowych zastosowanych do modułu. Parametr określa moduł.

GetCustomAttributes(Module, Boolean)

Pobiera tablicę atrybutów niestandardowych zastosowanych do modułu. Parametry określają moduł i zignorowaną opcję wyszukiwania.

GetCustomAttributes(Module, Type)

Pobiera tablicę atrybutów niestandardowych zastosowanych do modułu. Parametry określają moduł i typ atrybutu niestandardowego do wyszukania.

GetCustomAttributes(Module, Type, Boolean)

Pobiera tablicę atrybutów niestandardowych zastosowanych do modułu. Parametry określają moduł, typ atrybutu niestandardowego do wyszukania i zignorowaną opcję wyszukiwania.

GetCustomAttributes(ParameterInfo)

Pobiera tablicę atrybutów niestandardowych zastosowanych do parametru metody. Parametr określa parametr metody.

GetCustomAttributes(ParameterInfo, Boolean)

Pobiera tablicę atrybutów niestandardowych zastosowanych do parametru metody. Parametry określają parametr metody i określa, czy wyszukiwać elementy podrzędne parametru metody.

GetCustomAttributes(ParameterInfo, Type)

Pobiera tablicę atrybutów niestandardowych zastosowanych do parametru metody. Parametry określają parametr metody i typ atrybutu niestandardowego do wyszukania.

GetCustomAttributes(ParameterInfo, Type, Boolean)

Pobiera tablicę atrybutów niestandardowych zastosowanych do parametru metody. Parametry określają parametr metody, typ atrybutu niestandardowego do wyszukania i czy wyszukiwać przodków parametru metody.

GetHashCode()

Zwraca wartość skrótu dla tego wystąpienia.

GetType()

Type Pobiera bieżące wystąpienie.

(Odziedziczone po Object)
IsDefaultAttribute()

W przypadku zastąpienia w klasie pochodnej wskazuje, czy wartość tego wystąpienia jest wartością domyślną klasy pochodnej.

IsDefined(Assembly, Type)

Określa, czy do zestawu są stosowane jakiekolwiek atrybuty niestandardowe. Parametry określają zestaw i typ atrybutu niestandardowego do wyszukania.

IsDefined(Assembly, Type, Boolean)

Określa, czy do zestawu są stosowane jakiekolwiek atrybuty niestandardowe. Parametry określają zestaw, typ atrybutu niestandardowego do wyszukania i zignorowaną opcję wyszukiwania.

IsDefined(MemberInfo, Type)

Określa, czy jakiekolwiek atrybuty niestandardowe są stosowane do elementu członkowskiego typu. Parametry określają element członkowski i typ atrybutu niestandardowego do wyszukania.

IsDefined(MemberInfo, Type, Boolean)

Określa, czy jakiekolwiek atrybuty niestandardowe są stosowane do elementu członkowskiego typu. Parametry określają element członkowski, typ atrybutu niestandardowego do wyszukania i czy wyszukiwać elementów podrzędnych elementu członkowskiego.

IsDefined(Module, Type)

Określa, czy do modułu są stosowane jakiekolwiek atrybuty niestandardowe określonego typu. Parametry określają moduł i typ atrybutu niestandardowego do wyszukania.

IsDefined(Module, Type, Boolean)

Określa, czy do modułu są stosowane jakiekolwiek atrybuty niestandardowe. Parametry określają moduł, typ atrybutu niestandardowego do wyszukania i zignorowaną opcję wyszukiwania.

IsDefined(ParameterInfo, Type)

Określa, czy jakiekolwiek atrybuty niestandardowe są stosowane do parametru metody. Parametry określają parametr metody i typ atrybutu niestandardowego do wyszukania.

IsDefined(ParameterInfo, Type, Boolean)

Określa, czy jakiekolwiek atrybuty niestandardowe są stosowane do parametru metody. Parametry określają parametr metody, typ atrybutu niestandardowego do wyszukania i czy wyszukiwać przodków parametru metody.

Match(Object)

W przypadku zastąpienia w klasie pochodnej zwraca wartość wskazującą, czy to wystąpienie jest równe określonemu obiektowi.

MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
ToString()

Zwraca ciąg reprezentujący bieżący obiekt.

(Odziedziczone po Object)

Jawne implementacje interfejsu

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

Zestaw nazw jest mapowany na odpowiedni zestaw identyfikatorów wysyłania.

_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Pobiera informacje o typie obiektu, którego można użyć do pobrania informacji o typie interfejsu.

_Attribute.GetTypeInfoCount(UInt32)

Pobiera informację o liczbie typów interfejsów, jakie zawiera obiekt (0 lub 1).

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

Umożliwia dostęp do właściwości i metod udostępnianych przez obiekt.

Dotyczy

Bezpieczeństwo wątkowe

Ten typ jest bezpieczny wątkowo.

Zobacz też