Attribute 类

定义

表示自定义特性的基类。

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
继承
Attribute
派生
属性
实现

示例

下面的代码示例演示 了 的 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.

注解

Attribute 将预定义的系统信息或用户定义的自定义信息与目标元素相关联。 目标元素可以是程序集、类、构造函数、委托、枚举、事件、字段、接口、方法、可移植可执行文件模块、参数、属性、返回值、结构或其他属性。

属性提供的信息也称为元数据。 应用程序可以在运行时检查元数据,以控制程序处理数据的方式,或者在运行时之前由外部工具检查元数据,以控制应用程序本身的处理或维护方式。 例如,.NET 预定义并使用属性类型来控制运行时行为,某些编程语言使用属性类型来表示 .NET 通用类型系统不直接支持的语言功能。

所有属性类型都直接或间接从 Attribute 类派生。 特性可以应用于任何目标元素;多个属性可以应用于同一目标元素;和 属性可由派生自目标元素的元素继承。 AttributeTargets使用 类可指定应用特性的目标元素。

Attribute 提供了检索和测试自定义属性的便捷方法。 有关使用属性的详细信息,请参阅 应用属性属性

构造函数

Attribute()

初始化 Attribute 类的新实例。

属性

TypeId

在派生类中实现时,获取此 Attribute 的唯一标识符。

方法

Equals(Object)

返回一个值,该值指示此实例是否与指定的对象相等。

GetCustomAttribute(Assembly, Type)

检索应用于指定程序集的自定义属性。 参数指定程序集和要搜索的自定义属性的类型。

GetCustomAttribute(Assembly, Type, Boolean)

检索应用于程序集的自定义属性。 参数指定程序集、要搜索的自定义属性的类型以及忽略的搜索选项。

GetCustomAttribute(MemberInfo, Type)

检索应用于类型成员的自定义属性。 参数指定成员和要搜索的自定义属性的类型。

GetCustomAttribute(MemberInfo, Type, Boolean)

检索应用于类型成员的自定义属性。 参数指定成员、要搜索的自定义属性的类型以及是否搜索成员的祖先。

GetCustomAttribute(Module, Type)

检索应用于模块的自定义属性。 参数指定模块和要搜索的自定义属性的类型。

GetCustomAttribute(Module, Type, Boolean)

检索应用于模块的自定义属性。 参数指定模块、要搜索的自定义属性的类型以及忽略的搜索选项。

GetCustomAttribute(ParameterInfo, Type)

检索应用于方法参数的自定义属性。 参数指定方法参数和要搜索的自定义属性的类型。

GetCustomAttribute(ParameterInfo, Type, Boolean)

检索应用于方法参数的自定义属性。 参数指定方法参数、要搜索的自定义属性的类型以及是否搜索方法参数的祖先。

GetCustomAttributes(Assembly)

检索一个数组,它由应用于程序集的自定义属性组成。 参数指定程序集。

GetCustomAttributes(Assembly, Boolean)

检索一个数组,它由应用于程序集的自定义属性组成。 参数指定程序集及忽略的搜索选项。

GetCustomAttributes(Assembly, Type)

检索一个数组,它由应用于程序集的自定义属性组成。 参数指定程序集和要搜索的自定义属性的类型。

GetCustomAttributes(Assembly, Type, Boolean)

检索一个数组,它由应用于程序集的自定义属性组成。 参数指定程序集、要搜索的自定义属性的类型以及忽略的搜索选项。

GetCustomAttributes(MemberInfo)

检索应用于类型的成员的自定义属性的数组。 参数指定成员。

GetCustomAttributes(MemberInfo, Boolean)

检索应用于类型的成员的自定义属性的数组。 参数指定成员、要搜索的自定义属性的类型以及是否搜索成员的祖先。

GetCustomAttributes(MemberInfo, Type)

检索应用于类型的成员的自定义属性的数组。 参数指定成员和要搜索的自定义属性的类型。

GetCustomAttributes(MemberInfo, Type, Boolean)

检索应用于类型的成员的自定义属性的数组。 参数指定成员、要搜索的自定义属性的类型以及是否搜索成员的祖先。

GetCustomAttributes(Module)

检索应用于模块的自定义属性的数组。 参数指定模块。

GetCustomAttributes(Module, Boolean)

检索应用于模块的自定义属性的数组。 参数指定模块及忽略的搜索选项。

GetCustomAttributes(Module, Type)

检索应用于模块的自定义属性的数组。 参数指定模块和要搜索的自定义属性的类型。

GetCustomAttributes(Module, Type, Boolean)

检索应用于模块的自定义属性的数组。 参数指定模块、要搜索的自定义属性的类型以及忽略的搜索选项。

GetCustomAttributes(ParameterInfo)

检索应用于方法参数的自定义属性的数组。 参数指定方法参数。

GetCustomAttributes(ParameterInfo, Boolean)

检索应用于方法参数的自定义属性的数组。 参数指定方法参数以及是否搜索方法参数的祖先。

GetCustomAttributes(ParameterInfo, Type)

检索应用于方法参数的自定义属性的数组。 参数指定方法参数和要搜索的自定义属性的类型。

GetCustomAttributes(ParameterInfo, Type, Boolean)

检索应用于方法参数的自定义属性的数组。 参数指定方法参数、要搜索的自定义属性的类型以及是否搜索方法参数的祖先。

GetHashCode()

返回此实例的哈希代码。

GetType()

获取当前实例的 Type

(继承自 Object)
IsDefaultAttribute()

在派生类中重写时,指示此实例的值是否是派生类的默认值。

IsDefined(Assembly, Type)

确定是否将任意自定义属性应用于程序集。 参数指定程序集和要搜索的自定义属性的类型。

IsDefined(Assembly, Type, Boolean)

确定是否将任意自定义属性应用于程序集。 参数指定程序集、要搜索的自定义属性的类型以及忽略的搜索选项。

IsDefined(MemberInfo, Type)

确定是否将任意自定义属性应用于类型成员。 参数指定成员和要搜索的自定义属性的类型。

IsDefined(MemberInfo, Type, Boolean)

确定是否将任意自定义属性应用于类型成员。 参数指定成员、要搜索的自定义属性的类型以及是否搜索成员的祖先。

IsDefined(Module, Type)

确定是否将指定类型的任何自定义属性应用于模块。 参数指定模块和要搜索的自定义属性的类型。

IsDefined(Module, Type, Boolean)

确定是否将任意自定义属性应用于模块。 参数指定模块、要搜索的自定义属性的类型以及忽略的搜索选项。

IsDefined(ParameterInfo, Type)

确定是否将任意自定义属性应用于方法参数。 参数指定方法参数和要搜索的自定义属性的类型。

IsDefined(ParameterInfo, Type, Boolean)

确定是否将任意自定义属性应用于方法参数。 参数指定方法参数、要搜索的自定义属性的类型以及是否搜索方法参数的祖先。

Match(Object)

当在派生类中重写时,返回一个指示此实例是否等于指定对象的值。

MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
ToString()

返回表示当前对象的字符串。

(继承自 Object)

显式接口实现

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

将一组名称映射为对应的一组调度标识符。

_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

检索对象的类型信息,然后可以使用该信息获取接口的类型信息。

_Attribute.GetTypeInfoCount(UInt32)

检索对象提供的类型信息接口的数量(0 或 1)。

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

提供对某一对象公开的属性和方法的访问。

适用于

线程安全性

此类型是线程安全的。

另请参阅