Abrufen von Informationen aus AttributenRetrieving Information Stored in Attributes

Das Abrufen eines benutzerdefinierten Attributs ist ein einfacher Prozess.Retrieving a custom attribute is a simple process. Zuerst deklarieren Sie eine Instanz des Attributs, das Sie abrufen möchten.First, declare an instance of the attribute you want to retrieve. Dann verwenden Sie die Attribute.GetCustomAttribute-Methode, um das neue Attribut auf den Wert des abzurufenden Attributs zu initialisieren.Then, use the Attribute.GetCustomAttribute method to initialize the new attribute to the value of the attribute you want to retrieve. Sobald das neue Attribut initialisiert wurde, verwenden Sie einfach dessen Eigenschaften, um die Werte abzurufen.Once the new attribute is initialized, you simply use its properties to get the values.

Wichtig

In diesem Thema wird beschrieben, wie Attribute für Code abgerufen werden, der in den Ausführungskontext geladen wird.This topic describes how to retrieve attributes for code loaded into the execution context. Zum Abrufen von Attributen für Code, der in den reflexionsbezogenen Kontext geladen wurde, müssen Sie die CustomAttributeData-Klasse verwenden, wie in Vorgehensweise: Laden von Assemblys in den reflexionsbezogenen Kontext.To retrieve attributes for code loaded into the reflection-only context, you must use the CustomAttributeData class, as shown in How to: Load Assemblies into the Reflection-Only Context.

Dieser Abschnitt erläutert die folgenden Möglichkeiten zum Abrufen von Attributen:This section describes the following ways to retrieve attributes:

Abrufen einer einzelnen Instanz eines AttributsRetrieving a Single Instance of an Attribute

Im folgenden Beispiel wird die (im vorherigen Abschnitt beschriebene) DeveloperAttribute-Klasse auf die MainApp-Klasse auf Klassenebene angewendet.In the following example, the DeveloperAttribute (described in the previous section) is applied to the MainApp class on the class level. Die GetAttribute-Methode verwendet GetCustomAttribute, um die in DeveloperAttribute gespeicherten Werte auf Klassenebene abzurufen, bevor sie in der Konsole angezeigt werden.The GetAttribute method uses GetCustomAttribute to retrieve the values stored in DeveloperAttribute on the class level before displaying them to the console.

using namespace System;
using namespace System::Reflection;
using namespace CustomCodeAttributes;

[Developer("Joan Smith", "42", Reviewed = true)]
ref class MainApp
{
public:
    static void Main()
    {
        // Call function to get and display the attribute.
        GetAttribute(MainApp::typeid);
    }

    static void GetAttribute(Type^ t)
    {
        // Get instance of the attribute.
        DeveloperAttribute^ MyAttribute =
            (DeveloperAttribute^) Attribute::GetCustomAttribute(t, DeveloperAttribute::typeid);

        if (MyAttribute == nullptr)
        {
            Console::WriteLine("The attribute was not found.");
        }
        else
        {
            // Get the Name value.
            Console::WriteLine("The Name Attribute is: {0}." , MyAttribute->Name);
            // Get the Level value.
            Console::WriteLine("The Level Attribute is: {0}." , MyAttribute->Level);
            // Get the Reviewed value.
            Console::WriteLine("The Reviewed Attribute is: {0}." , MyAttribute->Reviewed);
        }
    }
};
using System;
using System.Reflection;
using CustomCodeAttributes;

[Developer("Joan Smith", "42", Reviewed = true)]
class MainApp
{
    public static void Main()
    {
        // Call function to get and display the attribute.
        GetAttribute(typeof(MainApp));
    }

    public static void GetAttribute(Type t)
    {
        // Get instance of the attribute.
        DeveloperAttribute MyAttribute =
            (DeveloperAttribute) Attribute.GetCustomAttribute(t, typeof (DeveloperAttribute));

        if (MyAttribute == null)
        {
            Console.WriteLine("The attribute was not found.");
        }
        else
        {
            // Get the Name value.
            Console.WriteLine("The Name Attribute is: {0}." , MyAttribute.Name);
            // Get the Level value.
            Console.WriteLine("The Level Attribute is: {0}." , MyAttribute.Level);
            // Get the Reviewed value.
            Console.WriteLine("The Reviewed Attribute is: {0}." , MyAttribute.Reviewed);
        }
    }
}
Imports System
Imports System.Reflection
Imports CustomCodeAttributes

<Developer("Joan Smith", "42", Reviewed := True)>
Class MainApp
    Public Shared Sub Main()
        ' Call function to get and display the attribute.
        GetAttribute(GetType(MainApp))
    End Sub

    Public Shared Sub GetAttribute(t As Type)
        ' Get instance of the attribute.
        Dim MyAttribute As DeveloperAttribute =
            CType(Attribute.GetCustomAttribute(t, GetType(DeveloperAttribute)), DeveloperAttribute)

        If MyAttribute Is Nothing Then
            Console.WriteLine("The attribute was not found.")
        Else
            ' Get the Name value.
            Console.WriteLine("The Name Attribute is: {0}." , MyAttribute.Name)
            ' Get the Level value.
            Console.WriteLine("The Level Attribute is: {0}." , MyAttribute.Level)
            ' Get the Reviewed value.
            Console.WriteLine("The Reviewed Attribute is: {0}." , MyAttribute.Reviewed)
        End If
    End Sub
End Class

Dieses Programm zeigt folgenden Text bei der Ausführung an.This program displays the following text when executed.

The Name Attribute is: Joan Smith.  
The Level Attribute is: 42.  
The Reviewed Attribute is: True.  

Wenn das Attribut nicht gefunden wird, initialisiert die GetCustomAttribute-Methode MyAttribute auf einen Nullwert.If the attribute is not found, the GetCustomAttribute method initializes MyAttribute to a null value. In diesem Beispiel wird MyAttribute auf eine solche Instanz geprüft und der Benutzer benachrichtigt, wenn kein Attribut gefunden wird.This example checks MyAttribute for such an instance and notifies the user if no attribute is found. Wenn das DeveloperAttribute nicht im Klassenbereich gefunden werden, wird die folgende Meldung in der Konsole angezeigt.If the DeveloperAttribute is not found in the class scope, the following message displays to the console.

The attribute was not found.   

In diesem Beispiel wird davon ausgegangen, dass sich die Attributdefinition im aktuellen Namespace befindet.This example assumes that the attribute definition is in the current namespace. Denken Sie daran, den Namespace zu importieren, in dem sich die Attributdefinition befindet, wenn diese nicht im aktuellen Namespace ist.Remember to import the namespace in which the attribute definition resides if it is not in the current namespace.

Abrufen mehrerer Instanzen eines Attributs in demselben Gültigkeitsbereich angewendetRetrieving Multiple Instances of an Attribute Applied to the Same Scope

Im vorherigen Beispiel werden die zu prüfende Klasse und das zu suchenden spezifische Attribut an GetCustomAttribute übergeben.In the previous example, the class to inspect and the specific attribute to find are passed to GetCustomAttribute. Dieser Code funktioniert gut, wenn nur eine Instanz eines Attributs auf Klassenebene angewendet wird.That code works well if only one instance of an attribute is applied on the class level. Wenn jedoch mehrere Instanzen eines Attributs auf derselben Klassenebene angewendet werden, ruft die GetCustomAttribute-Methode nicht alle Informationen ab.However, if multiple instances of an attribute are applied on the same class level, the GetCustomAttribute method does not retrieve all the information. In Fällen, in dem mehrere Instanzen des gleichen Attributs in demselben Gültigkeitsbereich angewendet werden, können Sie mithilfe von Attribute.GetCustomAttributes alle Instanzen eines Attributs in einem Array platzieren.In cases where multiple instances of the same attribute are applied to the same scope, you can use Attribute.GetCustomAttributes to place all instances of an attribute into an array. Wenn beispielsweise zwei Instanzen von DeveloperAttribute auf Klassenebene derselben Klasse angewendet werden, kann die GetAttribute-Methode zum Anzeigen der in beiden Attributen gefundenen Informationen geändert werden.For example, if two instances of DeveloperAttribute are applied on the class level of the same class, the GetAttribute method can be modified to display the information found in both attributes. Beim Anwenden mehrerer Attribute auf derselben Ebene müssen Sie beachten, dass das Attribut mit der AllowMultiple-Eigenschaft definiert wird, die in der AttributeUsageAttribute auf true gesetzt ist.Remember, to apply multiple attributes on the same level, the attribute must be defined with the AllowMultiple property set to true in the AttributeUsageAttribute.

Im folgenden Codebeispiel wird veranschaulicht, wie Sie mit der GetCustomAttributes-Methode ein Array erstellen, das auf alle Instanzen von DeveloperAttribute in einer bestimmten Klasse verweist.The following code example shows how to use the GetCustomAttributes method to create an array that references all instances of DeveloperAttribute in any given class. Die Werte aller Attribute werden anschließend in der Konsole angezeigt.The values of all attributes are then displayed to the console.

public:
    static void GetAttribute(Type^ t)
    {
        array<DeveloperAttribute^>^ MyAttributes =
            (array<DeveloperAttribute^>^) Attribute::GetCustomAttributes(t, DeveloperAttribute::typeid);

        if (MyAttributes->Length == 0)
        {
            Console::WriteLine("The attribute was not found.");
        }
        else
        {
            for (int i = 0 ; i < MyAttributes->Length; i++)
            {
                // Get the Name value.
                Console::WriteLine("The Name Attribute is: {0}." , MyAttributes[i]->Name);
                // Get the Level value.
                Console::WriteLine("The Level Attribute is: {0}." , MyAttributes[i]->Level);
                // Get the Reviewed value.
                Console::WriteLine("The Reviewed Attribute is: {0}.", MyAttributes[i]->Reviewed);
            }
        }
    }
public static void GetAttribute(Type t)
{
    DeveloperAttribute[] MyAttributes =
        (DeveloperAttribute[]) Attribute.GetCustomAttributes(t, typeof (DeveloperAttribute));

    if (MyAttributes.Length == 0)
    {
        Console.WriteLine("The attribute was not found.");
    }
    else
    {
        for (int i = 0 ; i < MyAttributes.Length ; i++)
        {
            // Get the Name value.
            Console.WriteLine("The Name Attribute is: {0}." , MyAttributes[i].Name);
            // Get the Level value.
            Console.WriteLine("The Level Attribute is: {0}." , MyAttributes[i].Level);
            // Get the Reviewed value.
            Console.WriteLine("The Reviewed Attribute is: {0}.", MyAttributes[i].Reviewed);
        }
    }
}
Public Shared Sub GetAttribute(t As Type)
    Dim MyAttributes() As DeveloperAttribute =
        CType(Attribute.GetCustomAttributes(t, GetType(DeveloperAttribute)), DeveloperAttribute())

    If MyAttributes.Length = 0 Then
        Console.WriteLine("The attribute was not found.")
    Else
        For i As Integer = 0 To MyAttributes.Length - 1
            ' Get the Name value.
            Console.WriteLine("The Name Attribute is: {0}." , MyAttributes(i).Name)
            ' Get the Level value.
            Console.WriteLine("The Level Attribute is: {0}." , MyAttributes(i).Level)
            ' Get the Reviewed value.
            Console.WriteLine("The Reviewed Attribute is: {0}.", MyAttributes(i).Reviewed)
        Next i
    End If
End Sub

Wenn keine Attribute gefunden werden, gibt dieser Code eine Warnung an den Benutzer aus.If no attributes are found, this code alerts the user. Andernfalls werden die in beiden Instanzen von DeveloperAttribute enthaltenen Informationen angezeigt.Otherwise, the information contained in both instances of DeveloperAttribute is displayed.

Abrufen mehrerer Instanzen eines Attributs auf unterschiedliche Bereiche angewendetRetrieving Multiple Instances of an Attribute Applied to Different Scopes

Die Methoden GetCustomAttributes und GetCustomAttribute durchsuchen nicht eine ganze Klasse, um Instanzen eines Attributs in dieser Klasse zurückzugeben.The GetCustomAttributes and GetCustomAttribute methods do not search an entire class and return all instances of an attribute in that class. Stattdessen suchen sie nur nach einer bestimmten Methode oder einem bestimmten Element zu einem gegebenen Zeitpunkt.Rather, they search only one specified method or member at a time. Angenommen, Sie haben eine Klasse, für die das gleiche Attribut auf jedes Element angewendet wurde. Um nun die Werte in den Attributen abzurufen, die auf diese Elemente angewendet wurden, müssen Sie jede Methode oder jedes Element einzeln für GetCustomAttributes und GetCustomAttribute bereitstellen.If you have a class with the same attribute applied to every member and you want to retrieve the values in all the attributes applied to those members, you must supply every method or member individually to GetCustomAttributes and GetCustomAttribute.

Im folgenden Codebeispiel wird eine Klasse als Parameter akzeptiert und nach dem DeveloperAttribute (zuvor definiert) auf Klassenebene und in jeder einzelnen Methode dieser Klasse gesucht.The following code example takes a class as a parameter and searches for the DeveloperAttribute (defined previously) on the class level and on every individual method of that class.

public:
    static void GetAttribute(Type^ t)
    {
        DeveloperAttribute^ att;

        // Get the class-level attributes.

        // Put the instance of the attribute on the class level in the att object.
        att = (DeveloperAttribute^) Attribute::GetCustomAttribute (t, DeveloperAttribute::typeid);

        if (att == nullptr)
        {
            Console::WriteLine("No attribute in class {0}.\n", t->ToString());
        }
        else
        {
            Console::WriteLine("The Name Attribute on the class level is: {0}.", att->Name);
            Console::WriteLine("The Level Attribute on the class level is: {0}.", att->Level);
            Console::WriteLine("The Reviewed Attribute on the class level is: {0}.\n", att->Reviewed);
        }

        // Get the method-level attributes.

        // Get all methods in this class, and put them
        // in an array of System.Reflection.MemberInfo objects.
        array<MemberInfo^>^ MyMemberInfo = t->GetMethods();

        // Loop through all methods in this class that are in the
        // MyMemberInfo array.
        for (int i = 0; i < MyMemberInfo->Length; i++)
        {
            att = (DeveloperAttribute^) Attribute::GetCustomAttribute(MyMemberInfo[i], DeveloperAttribute::typeid);
            if (att == nullptr)
            {
                Console::WriteLine("No attribute in member function {0}.\n" , MyMemberInfo[i]->ToString());
            }
            else
            {
                Console::WriteLine("The Name Attribute for the {0} member is: {1}.",
                    MyMemberInfo[i]->ToString(), att->Name);
                Console::WriteLine("The Level Attribute for the {0} member is: {1}.",
                    MyMemberInfo[i]->ToString(), att->Level);
                Console::WriteLine("The Reviewed Attribute for the {0} member is: {1}.\n",
                    MyMemberInfo[i]->ToString(), att->Reviewed);
            }
        }
    }
public static void GetAttribute(Type t)
{
    DeveloperAttribute att;

    // Get the class-level attributes.

    // Put the instance of the attribute on the class level in the att object.
    att = (DeveloperAttribute) Attribute.GetCustomAttribute (t, typeof (DeveloperAttribute));

    if (att == null)
    {
        Console.WriteLine("No attribute in class {0}.\n", t.ToString());
    }
    else
    {
        Console.WriteLine("The Name Attribute on the class level is: {0}.", att.Name);
        Console.WriteLine("The Level Attribute on the class level is: {0}.", att.Level);
        Console.WriteLine("The Reviewed Attribute on the class level is: {0}.\n", att.Reviewed);
    }

    // Get the method-level attributes.

    // Get all methods in this class, and put them
    // in an array of System.Reflection.MemberInfo objects.
    MemberInfo[] MyMemberInfo = t.GetMethods();

    // Loop through all methods in this class that are in the
    // MyMemberInfo array.
    for (int i = 0; i < MyMemberInfo.Length; i++)
    {
        att = (DeveloperAttribute) Attribute.GetCustomAttribute(MyMemberInfo[i], typeof (DeveloperAttribute));
        if (att == null)
        {
            Console.WriteLine("No attribute in member function {0}.\n" , MyMemberInfo[i].ToString());
        }
        else
        {
            Console.WriteLine("The Name Attribute for the {0} member is: {1}.",
                MyMemberInfo[i].ToString(), att.Name);
            Console.WriteLine("The Level Attribute for the {0} member is: {1}.",
                MyMemberInfo[i].ToString(), att.Level);
            Console.WriteLine("The Reviewed Attribute for the {0} member is: {1}.\n",
                MyMemberInfo[i].ToString(), att.Reviewed);
        }
    }
}
Public Shared Sub GetAttribute(t As Type)
    Dim att As DeveloperAttribute

    ' Get the class-level attributes.

    ' Put the instance of the attribute on the class level in the att object.
    att = CType(Attribute.GetCustomAttribute(t, GetType(DeveloperAttribute)), DeveloperAttribute)

    If att Is Nothing
        Console.WriteLine("No attribute in class {0}.\n", t.ToString())
    Else
        Console.WriteLine("The Name Attribute on the class level is: {0}.", att.Name)
        Console.WriteLine("The Level Attribute on the class level is: {0}.", att.Level)
        Console.WriteLine("The Reviewed Attribute on the class level is: {0}.\n", att.Reviewed)
    End If

    ' Get the method-level attributes.

    ' Get all methods in this class, and put them
    ' in an array of System.Reflection.MemberInfo objects.
    Dim MyMemberInfo() As MemberInfo = t.GetMethods()

    ' Loop through all methods in this class that are in the
    ' MyMemberInfo array.
    For i As Integer = 0 To MyMemberInfo.Length - 1
        att = CType(Attribute.GetCustomAttribute(MyMemberInfo(i), _
            GetType(DeveloperAttribute)), DeveloperAttribute)
        If att Is Nothing Then
            Console.WriteLine("No attribute in member function {0}.\n" , MyMemberInfo(i).ToString())
        Else
            Console.WriteLine("The Name Attribute for the {0} member is: {1}.",
                MyMemberInfo(i).ToString(), att.Name)
            Console.WriteLine("The Level Attribute for the {0} member is: {1}.",
                MyMemberInfo(i).ToString(), att.Level)
            Console.WriteLine("The Reviewed Attribute for the {0} member is: {1}.\n",
                MyMemberInfo(i).ToString(), att.Reviewed)
        End If
    Next
End Sub

Wenn auf Methoden- oder Klassenebene keine Instanzen von DeveloperAttribute gefunden werden, benachrichtigt die GetAttribute-Methode den Benutzer, dass keine Attribute gefunden wurden, und zeigt den Namen der Methode oder Klasse an, die das Attribut nicht enthält.If no instances of the DeveloperAttribute are found on the method level or class level, the GetAttribute method notifies the user that no attributes were found and displays the name of the method or class that does not contain the attribute. Wenn ein Attribut gefunden wird, werden die Felder Name, Level und Reviewed in der Konsole angezeigt.If an attribute is found, the Name, Level, and Reviewed fields are displayed to the console.

Sie können die Elemente der Type-Klasse verwenden, um die einzelnen Methoden und Elemente der übergebenen Klasse abzurufen.You can use the members of the Type class to get the individual methods and members in the passed class. In diesem Beispiel wird zuerst das Type-Objekt abgefragt, um Attributinformationen für die Klassenebene abzurufen.This example first queries the Type object to get attribute information for the class level. Als Nächstes wird Type.GetMethods verwendet, um Instanzen aller Methoden in einem Array von System.Reflection.MemberInfo-Objekten zu platzieren, um Attributinformationen für die Methodenebene abzurufen.Next, it uses Type.GetMethods to place instances of all methods into an array of System.Reflection.MemberInfo objects to retrieve attribute information for the method level. Sie können mithilfe der Type.GetProperties-Methode nach Attributen auf Eigenschaftenebene oder mithilfe von Type.GetConstructors nach Attributen auf Konstruktorebene suchen.You can also use the Type.GetProperties method to check for attributes on the property level or Type.GetConstructors to check for attributes on the constructor level.

Siehe auchSee also