Attribute Класс

Определение

Represents the base class for custom attributes.Represents the base class for custom attributes.

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.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public abstract class Attribute : System.Runtime.InteropServices._Attribute
[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple=false, Inherited=true)]
[System.Serializable]
public abstract class Attribute
type Attribute = class
type Attribute = class
    interface _Attribute
Public MustInherit Class Attribute
Public MustInherit Class Attribute
Implements _Attribute
Наследование
Attribute
Производный
Атрибуты
Реализации

Примеры

В следующем примере кода показано использование Attribute.The following code example demonstrates the usage of 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.
 */
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.

Комментарии

Класс Attribute связывает стандартные системные или нестандартные пользовательские сведения с целевым элементом.The Attribute class associates predefined system information or user-defined custom information with a target element. Целевой элемент может быть сборкой, классом, конструктором, делегатом, перечислением, событием, полем, интерфейсом, методом, модулем переносимого исполняемого файла, параметром, свойством, возвращаемым значением, структурой или другим аттрибутом.A target element can be an assembly, class, constructor, delegate, enum, event, field, interface, method, portable executable file module, parameter, property, return value, struct, or another attribute.

Сведения, предоставленные с помощью атрибута, также называют метаданными.Information provided by an attribute is also known as metadata. Метаданные могут анализироваться приложением во время выполнения для управления обработкой данных в программе либо внешними средствами до времени выполнения для управления обработкой или обслуживанием самого приложения.Metadata can be examined at run time by your application to control how your program processes data, or before run time by external tools to control how your application itself is processed or maintained. Например, платформа .NET Framework предопределяет и использует типы атрибутов для управления поведением во время выполнения, а некоторые языки программирования используют типы атрибутов для представления языковых функций, не поддерживаемых непосредственно системой общих типов .NET Framework.For example, the .NET Framework predefines and uses attribute types to control run-time behavior, and some programming languages use attribute types to represent language features not directly supported by the .NET Framework common type system.

Все типы атрибутов являются непосредственно или косвенно производными от класса Attribute.All attribute types derive directly or indirectly from the Attribute class. Атрибуты могут применяться к любому целевому элементу; несколько атрибутов могут применяться к одному и тому же целевому элементу; также атрибуты могут наследоваться элементами, производными от целевого элемента.Attributes can be applied to any target element; multiple attributes can be applied to the same target element; and attributes can be inherited by an element derived from a target element. Используйте класс AttributeTargets для указания целевого элемента, к которому применяется атрибут.Use the AttributeTargets class to specify the target element to which the attribute is applied.

Класс Attribute предоставляет удобные методы для извлечения и проверки настраиваемых атрибутов.The Attribute class provides convenient methods to retrieve and test custom attributes. Дополнительные сведения об использовании атрибутов см. в разделах Применение атрибутов и Атрибуты.For more information about using attributes, see Applying Attributes and Attributes.

Конструкторы

Attribute()

Initializes a new instance of the Attribute class.Initializes a new instance of the Attribute class.

Свойства

TypeId

When implemented in a derived class, gets a unique identifier for this Attribute.When implemented in a derived class, gets a unique identifier for this Attribute.

Методы

Equals(Object)

Returns a value that indicates whether this instance is equal to a specified object.Returns a value that indicates whether this instance is equal to a specified object.

GetCustomAttribute(Assembly, Type)

Retrieves a custom attribute applied to a specified assembly.Retrieves a custom attribute applied to a specified assembly. Parameters specify the assembly and the type of the custom attribute to search for.Parameters specify the assembly and the type of the custom attribute to search for.

GetCustomAttribute(Assembly, Type, Boolean)

Retrieves a custom attribute applied to an assembly.Retrieves a custom attribute applied to an assembly. Parameters specify the assembly, the type of the custom attribute to search for, and an ignored search option.Parameters specify the assembly, the type of the custom attribute to search for, and an ignored search option.

GetCustomAttribute(MemberInfo, Type)

Retrieves a custom attribute applied to a member of a type.Retrieves a custom attribute applied to a member of a type. Parameters specify the member, and the type of the custom attribute to search for.Parameters specify the member, and the type of the custom attribute to search for.

GetCustomAttribute(MemberInfo, Type, Boolean)

Retrieves a custom attribute applied to a member of a type.Retrieves a custom attribute applied to a member of a type. Parameters specify the member, the type of the custom attribute to search for, and whether to search ancestors of the member.Parameters specify the member, the type of the custom attribute to search for, and whether to search ancestors of the member.

GetCustomAttribute(Module, Type)

Retrieves a custom attribute applied to a module.Retrieves a custom attribute applied to a module. Parameters specify the module, and the type of the custom attribute to search for.Parameters specify the module, and the type of the custom attribute to search for.

GetCustomAttribute(Module, Type, Boolean)

Retrieves a custom attribute applied to a module.Retrieves a custom attribute applied to a module. Parameters specify the module, the type of the custom attribute to search for, and an ignored search option.Parameters specify the module, the type of the custom attribute to search for, and an ignored search option.

GetCustomAttribute(ParameterInfo, Type)

Retrieves a custom attribute applied to a method parameter.Retrieves a custom attribute applied to a method parameter. Parameters specify the method parameter, and the type of the custom attribute to search for.Parameters specify the method parameter, and the type of the custom attribute to search for.

GetCustomAttribute(ParameterInfo, Type, Boolean)

Retrieves a custom attribute applied to a method parameter.Retrieves a custom attribute applied to a method parameter. Parameters specify the method parameter, the type of the custom attribute to search for, and whether to search ancestors of the method parameter.Parameters specify the method parameter, the type of the custom attribute to search for, and whether to search ancestors of the method parameter.

GetCustomAttributes(Assembly)

Retrieves an array of the custom attributes applied to an assembly.Retrieves an array of the custom attributes applied to an assembly. A parameter specifies the assembly.A parameter specifies the assembly.

GetCustomAttributes(Assembly, Boolean)

Retrieves an array of the custom attributes applied to an assembly.Retrieves an array of the custom attributes applied to an assembly. Parameters specify the assembly, and an ignored search option.Parameters specify the assembly, and an ignored search option.

GetCustomAttributes(Assembly, Type)

Retrieves an array of the custom attributes applied to an assembly.Retrieves an array of the custom attributes applied to an assembly. Parameters specify the assembly, and the type of the custom attribute to search for.Parameters specify the assembly, and the type of the custom attribute to search for.

GetCustomAttributes(Assembly, Type, Boolean)

Retrieves an array of the custom attributes applied to an assembly.Retrieves an array of the custom attributes applied to an assembly. Parameters specify the assembly, the type of the custom attribute to search for, and an ignored search option.Parameters specify the assembly, the type of the custom attribute to search for, and an ignored search option.

GetCustomAttributes(MemberInfo)

Retrieves an array of the custom attributes applied to a member of a type.Retrieves an array of the custom attributes applied to a member of a type. A parameter specifies the member.A parameter specifies the member.

GetCustomAttributes(MemberInfo, Boolean)

Retrieves an array of the custom attributes applied to a member of a type.Retrieves an array of the custom attributes applied to a member of a type. Parameters specify the member, the type of the custom attribute to search for, and whether to search ancestors of the member.Parameters specify the member, the type of the custom attribute to search for, and whether to search ancestors of the member.

GetCustomAttributes(MemberInfo, Type)

Retrieves an array of the custom attributes applied to a member of a type.Retrieves an array of the custom attributes applied to a member of a type. Parameters specify the member, and the type of the custom attribute to search for.Parameters specify the member, and the type of the custom attribute to search for.

GetCustomAttributes(MemberInfo, Type, Boolean)

Retrieves an array of the custom attributes applied to a member of a type.Retrieves an array of the custom attributes applied to a member of a type. Parameters specify the member, the type of the custom attribute to search for, and whether to search ancestors of the member.Parameters specify the member, the type of the custom attribute to search for, and whether to search ancestors of the member.

GetCustomAttributes(Module)

Retrieves an array of the custom attributes applied to a module.Retrieves an array of the custom attributes applied to a module. A parameter specifies the module.A parameter specifies the module.

GetCustomAttributes(Module, Boolean)

Retrieves an array of the custom attributes applied to a module.Retrieves an array of the custom attributes applied to a module. Parameters specify the module, and an ignored search option.Parameters specify the module, and an ignored search option.

GetCustomAttributes(Module, Type)

Retrieves an array of the custom attributes applied to a module.Retrieves an array of the custom attributes applied to a module. Parameters specify the module, and the type of the custom attribute to search for.Parameters specify the module, and the type of the custom attribute to search for.

GetCustomAttributes(Module, Type, Boolean)

Retrieves an array of the custom attributes applied to a module.Retrieves an array of the custom attributes applied to a module. Parameters specify the module, the type of the custom attribute to search for, and an ignored search option.Parameters specify the module, the type of the custom attribute to search for, and an ignored search option.

GetCustomAttributes(ParameterInfo)

Retrieves an array of the custom attributes applied to a method parameter.Retrieves an array of the custom attributes applied to a method parameter. A parameter specifies the method parameter.A parameter specifies the method parameter.

GetCustomAttributes(ParameterInfo, Boolean)

Retrieves an array of the custom attributes applied to a method parameter.Retrieves an array of the custom attributes applied to a method parameter. Parameters specify the method parameter, and whether to search ancestors of the method parameter.Parameters specify the method parameter, and whether to search ancestors of the method parameter.

GetCustomAttributes(ParameterInfo, Type)

Retrieves an array of the custom attributes applied to a method parameter.Retrieves an array of the custom attributes applied to a method parameter. Parameters specify the method parameter, and the type of the custom attribute to search for.Parameters specify the method parameter, and the type of the custom attribute to search for.

GetCustomAttributes(ParameterInfo, Type, Boolean)

Retrieves an array of the custom attributes applied to a method parameter.Retrieves an array of the custom attributes applied to a method parameter. Parameters specify the method parameter, the type of the custom attribute to search for, and whether to search ancestors of the method parameter.Parameters specify the method parameter, the type of the custom attribute to search for, and whether to search ancestors of the method parameter.

GetHashCode()

Returns the hash code for this instance.Returns the hash code for this instance.

GetType()

Возвращает объект Type для текущего экземпляра.Gets the Type of the current instance.

(Унаследовано от Object)
IsDefaultAttribute()

When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

IsDefined(Assembly, Type)

Determines whether any custom attributes are applied to an assembly.Determines whether any custom attributes are applied to an assembly. Parameters specify the assembly, and the type of the custom attribute to search for.Parameters specify the assembly, and the type of the custom attribute to search for.

IsDefined(Assembly, Type, Boolean)

Determines whether any custom attributes are applied to an assembly.Determines whether any custom attributes are applied to an assembly. Parameters specify the assembly, the type of the custom attribute to search for, and an ignored search option.Parameters specify the assembly, the type of the custom attribute to search for, and an ignored search option.

IsDefined(MemberInfo, Type)

Determines whether any custom attributes are applied to a member of a type.Determines whether any custom attributes are applied to a member of a type. Parameters specify the member, and the type of the custom attribute to search for.Parameters specify the member, and the type of the custom attribute to search for.

IsDefined(MemberInfo, Type, Boolean)

Determines whether any custom attributes are applied to a member of a type.Determines whether any custom attributes are applied to a member of a type. Parameters specify the member, the type of the custom attribute to search for, and whether to search ancestors of the member.Parameters specify the member, the type of the custom attribute to search for, and whether to search ancestors of the member.

IsDefined(Module, Type)

Determines whether any custom attributes of a specified type are applied to a module.Determines whether any custom attributes of a specified type are applied to a module. Parameters specify the module, and the type of the custom attribute to search for.Parameters specify the module, and the type of the custom attribute to search for.

IsDefined(Module, Type, Boolean)

Determines whether any custom attributes are applied to a module.Determines whether any custom attributes are applied to a module. Parameters specify the module, the type of the custom attribute to search for, and an ignored search option.Parameters specify the module, the type of the custom attribute to search for, and an ignored search option.

IsDefined(ParameterInfo, Type)

Determines whether any custom attributes are applied to a method parameter.Determines whether any custom attributes are applied to a method parameter. Parameters specify the method parameter, and the type of the custom attribute to search for.Parameters specify the method parameter, and the type of the custom attribute to search for.

IsDefined(ParameterInfo, Type, Boolean)

Determines whether any custom attributes are applied to a method parameter.Determines whether any custom attributes are applied to a method parameter. Parameters specify the method parameter, the type of the custom attribute to search for, and whether to search ancestors of the method parameter.Parameters specify the method parameter, the type of the custom attribute to search for, and whether to search ancestors of the method parameter.

Match(Object)

When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

MemberwiseClone()

Создает неполную копию текущего объекта Object.Creates a shallow copy of the current Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.Returns a string that represents the current object.

(Унаследовано от Object)

Явные реализации интерфейса

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

Maps a set of names to a corresponding set of dispatch identifiers.Maps a set of names to a corresponding set of dispatch identifiers.

_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Retrieves the type information for an object, which can be used to get the type information for an interface.Retrieves the type information for an object, which can be used to get the type information for an interface.

_Attribute.GetTypeInfoCount(UInt32)

Retrieves the number of type information interfaces that an object provides (either 0 or 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1).

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

Provides access to properties and methods exposed by an object.Provides access to properties and methods exposed by an object.

Применяется к

Потокобезопасность

Данный тип потокобезопасен.This type is thread safe.

Дополнительно