资料来源:MSDN-AttributeUsage

开篇:今天看到老赵的一篇博文,说的关于Attribute操作的性能优化,对其中的基本概念不甚了解,在此Mark一下

AttributeUsage

  Msdn的定义如下:确定可以如何使用自定义属性类。

  AttributeUsage 是一个可应用于自定义属性定义的属性,自定义属性定义来控制如何应用新属性。

 

  它有两个重载:

    AttributeUsage(AttributeTargets)

    Attributeusage(AttributeTargets,AllowMultiple,Inherited)

 

   其中AllowMultiple标识是否可重复定义此Attribute

   其中Inherited标识是否可继承

   AttributeTargets是一个枚举类型,详细应用可参考MSDN上的示例


成员名称 说明
Attribute标记AttributeUsageAttribute标记AttributeUsage Assembly 可以对程序集应用属性。
Attribute标记AttributeUsageAttribute标记AttributeUsage Module 可以对模块应用属性。
Attribute标记AttributeUsageAttribute标记AttributeUsage Class 可以对类应用属性。
Attribute标记AttributeUsageAttribute标记AttributeUsage Struct 可以对结构应用属性,即值类型。
Attribute标记AttributeUsageAttribute标记AttributeUsage Enum 可以对枚举应用属性。
Attribute标记AttributeUsageAttribute标记AttributeUsage Constructor 可以对构造函数应用属性。
Attribute标记AttributeUsageAttribute标记AttributeUsage Method 可以对方法应用属性。
Attribute标记AttributeUsageAttribute标记AttributeUsage Property 可以对属性 (Property) 应用属性 (Attribute)。
Attribute标记AttributeUsageAttribute标记AttributeUsage Field 可以对字段应用属性。
Attribute标记AttributeUsageAttribute标记AttributeUsage Event 可以对事件应用属性。
Attribute标记AttributeUsageAttribute标记AttributeUsage Interface 可以对接口应用属性。
Attribute标记AttributeUsageAttribute标记AttributeUsage Parameter 可以对参数应用属性。
Attribute标记AttributeUsageAttribute标记AttributeUsage Delegate 可以对委托应用属性。
Attribute标记AttributeUsageAttribute标记AttributeUsage ReturnValue 可以对返回值应用属性。
Attribute标记AttributeUsageAttribute标记AttributeUsage GenericParameter 可以对泛型参数应用属性。
Attribute标记AttributeUsageAttribute标记AttributeUsage All

可以对任何应用程序元素应用属性。

多个目标类型可同时进行“或”运算

  测试的代码:

          

)]
    public class TestAttribute : Attribute
    {
    }
    
//应用类
    [Test] //若Attribute类名称以Attribute结尾,则自动去掉
    public class TestAtt
    {
    }

 

)]
    public class TestAttribute : Attribute
    {
    }
    
//应用类
    public class TestAtt
    {
        [Test]
//AttributeUsage中的区域定义(AttributeTargets)必须严格遵守
        public void TestTT()
        { }
    }

 

 其他:

必须定义继承Attribute的类

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

AttributeUsage 是 AttributeUsageAttribute 的别名

 

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-30
  • 2021-08-01
  • 2021-10-20
  • 2022-12-23
  • 2021-05-31
猜你喜欢
  • 2022-02-08
  • 2021-06-23
  • 2022-12-23
  • 2021-10-10
  • 2021-08-29
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案