AttributeUsage(C# 编程指南)

更新:2007 年 11 月

确定可以如何使用自定义属性类。AttributeUsage 是一个可应用于自定义属性定义的属性,自定义属性定义来控制如何应用新属性。显式应用的默认设置与此类似:

[System.AttributeUsage(System.AttributeTargets.All, 
                   AllowMultiple=false, 
                   Inherited=true)]
class NewAttribute : System.Attribute { }

在本例中,NewAttribute 类可应用于任何支持属性的代码实体,但是对每个实体只可应用一次。当应用于基类时,它可由派生类继承。

AllowMultiple 和 Inherited 参数是可选的,所以此代码具有相同的效果:

[System.AttributeUsage(System.AttributeTargets.All)]
class NewAttribute : System.Attribute { }

第一个 AttributeUsage 参数必须是 AttributeTargets 枚举的一个或多个元素。多个目标类型可同时进行“或”运算,如下例所示:

using System;
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
class NewPropertyOrFieldAttribute : Attribute { }

如果 AllowMultiple 参数设置为 true,则返回属性可对单个实体应用多次,如下例所示:

using System;
[AttributeUsage(AttributeTargets.Class, AllowMultiple=true)]
class MultiUseAttr : Attribute { }

[MultiUseAttr][MultiUseAttr]
class Class1 { }

[MultiUseAttr, MultiUseAttr]
class Class2 { }

在这种情况下,由于 AllowMultiple 设置为 true,MultiUseAttr 可反复应用。所示的应用多个属性的这两种格式均有效。

如果 Inherited 设置为 false,则该属性不由从属性化的类派生的类继承。例如:

using System;
[AttributeUsage(AttributeTargets.Class, Inherited=false)]
class Attr1 : Attribute { }

[Attr1]
class BClass { }

class DClass : BClass { }

在这种情况下,Attr1 不通过继承应用于 DClass。

备注

AttributeUsage 属性是一个单用途属性 — 它无法对相同的类应用多次。AttributeUsage 是 AttributeUsageAttribute 的别名。

有关更多信息,请参见 使用反射访问属性(C# 编程指南)

示例

下面的示例将阐释 Inherited 参数和 AllowMultiple 参数对 AttributeUsage 属性的效果,以及如何才能枚举应用于类的自定义属性。

using System;

// Create some custom attributes:
[AttributeUsage(System.AttributeTargets.Class, Inherited=false)]
class A1 : System.Attribute { }

[AttributeUsage(System.AttributeTargets.Class)]
class A2 : System.Attribute { }

[AttributeUsage(System.AttributeTargets.Class, AllowMultiple=true)]
class A3 : System.Attribute { }

// Apply custom attributes to classes:
[A1,A2]
class BaseClass { }

[A3,A3]
class DerivedClass : BaseClass { }

public class TestAttributeUsage
{
    static void Main()
    {
        BaseClass b = new BaseClass();
        DerivedClass d = new DerivedClass();

        // Display custom attributes for each class.
        Console.WriteLine("Attributes on Base Class:");
        object[] attrs = b.GetType().GetCustomAttributes(true);
        foreach (Attribute attr in attrs)
        {
            Console.WriteLine(attr);
        }
 
        Console.WriteLine("Attributes on Derived Class:");
        attrs = d.GetType().GetCustomAttributes(true);
        foreach (Attribute attr in attrs)
        {
            Console.WriteLine(attr);
        }
    }
}

示例输出

Attributes on Base Class:
A1
A2
Attributes on Derived Class:
A3
A3
A2

请参见

概念

C# 编程指南

参考

反射(C# 编程指南)

属性(C# 编程指南)

使用属性(C# 编程指南)

消除属性目标的歧义性(C# 编程指南)

创建自定义属性(C# 编程指南)

使用反射访问属性(C# 编程指南)

Attribute

System.Reflection