Aracılığıyla paylaş


Accessing Custom Attributes

After attributes have been associated with program elements, reflection can be used to query their existence and values. In the .NET Framework version 1.0 and 1.1, custom attributes are examined in the execution context. The .NET Framework version 2.0 provides a new load context, the reflection-only context, which can be used to examine code that cannot be loaded for execution.

The Reflection-Only Context

Code loaded into the reflection-only context cannot be executed. This means that instances of custom attributes cannot be created, because that would require executing their constructors. To load and examine custom attributes in the reflection-only context, use the CustomAttributeData class. You can obtain instances of this class by using the appropriate overload of the static CustomAttributeData.GetCustomAttributes method. See How to: Load Assemblies into the Reflection-Only Context.

The Execution Context

The main reflection methods to query attributes in the execution context are MemberInfo.GetCustomAttributes and Attribute.GetCustomAttributes.

The accessibility of a custom attribute is checked with respect to the assembly in which it is attached. This is equivalent to checking whether a method on a type in the assembly in which the custom attribute is attached can call the constructor of the custom attribute.

Methods such as Assembly.GetCustomAttributes(Boolean) check the visibility and accessibility of the type argument. Only code in the assembly that contains the user-defined type can retrieve a custom attribute of that type using GetCustomAttributes.

The following C# example is a typical custom attribute design pattern. It illustrates the runtime custom attribute reflection model.

System.DLL
public class DescriptionAttribute : Attribute
{
}

System.Web.DLL
internal class MyDescriptionAttribute : DescriptionAttribute
{
}

public class LocalizationExtenderProvider
{
    [MyDescriptionAttribute(...)]
    public CultureInfo GetLanguage(...)
    {
    }
}

If the runtime is attempting to retrieve the custom attributes for the public custom attribute type DescriptionAttribute attached to the GetLanguage method, it performs the following actions:

  1. The runtime checks that the type argument DescriptionAttribute to Type.GetCustomAttributes(Type type) is public, and therefore is visible and accessible.

  2. The runtime checks that the user-defined type MyDescriptionAttribute that is derived from DescriptionAttribute is visible and accessible within the System.Web.DLL assembly, where it is attached to the method GetLanguage().

  3. The runtime checks that the constructor of MyDescriptionAttribute is visible and accessible within the System.Web.DLL assembly.

  4. The runtime calls the constructor of MyDescriptionAttribute with the custom attribute parameters and returns the new object to the caller.

The custom attribute reflection model could leak instances of user-defined types outside the assembly in which the type is defined. This is no different from the members in the runtime system library that return instances of user-defined types, such as Type.GetMethods() returning an array of RuntimeMethodInfo objects. To prevent a client from discovering information about a user-defined custom attribute type, define the type's members to be nonpublic.

The following example demonstrates the basic way of using reflection to get access to custom attributes.

Imports System

Public Class ExampleAttribute
    Inherits Attribute

    Private stringVal As String

    Public Sub New()
        stringVal = "This is the default string."
    End Sub

    Public Property StringValue() As String
        Get
            Return stringVal
        End Get
        Set(Value As String)
            stringVal = Value
        End Set
    End Property
End Class

<Example(StringValue := "This is a string.")> _
Class Class1
    Public Shared Sub Main()
    Dim info As System.Reflection.MemberInfo = GetType(Class1)
        For Each attrib As Object In info.GetCustomAttributes(true)
            Console.WriteLine(attrib)
        Next attrib
    End Sub
End Class
using System;

public class ExampleAttribute : Attribute
{
    private string stringVal;

    public ExampleAttribute()
    {
        stringVal = "This is the default string.";
    }

    public string StringValue
    {
        get { return stringVal; }
        set { stringVal = value; }
    }
}

[Example(StringValue="This is a string.")]
class Class1
{
    public static void Main()
    {
        System.Reflection.MemberInfo info = typeof(Class1);
        foreach (object attrib in info.GetCustomAttributes(true))
        {
            Console.WriteLine(attrib);
        }
    }
}
using namespace System;

public ref class ExampleAttribute : Attribute
{
private:
    String^ stringVal;

public:
    ExampleAttribute()
    {
        stringVal = "This is the default string.";
    }


    property String^ StringValue
    {
        String^ get() { return stringVal; }
        void set(String^ value) { stringVal = value; }
    }
};

[Example(StringValue="This is a string.")]
public ref class Class1
{
public:
    static void Main()
    {
        System::Reflection::MemberInfo^ info = Type::GetType("Class1");
        for each (Object^ attrib in info->GetCustomAttributes(true))
        {
            Console::WriteLine(attrib);
        }
    }
};

int main()
{
    Class1::Main();
}

See Also

Reference

MemberInfo.GetCustomAttributes

Attribute.GetCustomAttributes

Concepts

Viewing Type Information

Security Considerations for Reflection