• 特性AttributeUsage


    特性AttributeUsage 基本介绍:

    AttributeUsage 属性(第 17.4.1 节)用于描述使用属性类的方式。

    AttributeUsage 具有一个定位参数(第 17.1.2 节),该参数使属性类能够指定自己可以用在那种声明上。示例

    using System;
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)]
    public class SimpleAttribute: Attribute 
    {
       ...
    }

    定义了一个名为 SimpleAttribute 的属性类,此属性类只能放在类声明和接口声明上。示例

    [Simple] class Class1 {...}
    [Simple] interface Interface1 {...}

    显示了 Simple 属性的几种用法。虽然此属性是用名称 SimpleAttribute 定义的,但在使用时可以省略 Attribute 后缀,从而得到简称 Simple。因此,上例在语义上等效于:

    [SimpleAttribute] class Class1 {...}
    [SimpleAttribute] interface Interface1 {...}

    AttributeUsage 还具有一个名为 AllowMultiple 的命名参数(第 17.1.2 节),此参数用于说明对于某个给定实体,是否可以多次使用该属性。如果属性类的 AllowMultiple 为 true,则此属性类是多次性属性类,可以在一个实体上多次被应用。如果属性类的 AllowMultiple 为 false 或未指定的,则此属性类是一次性属性类,在一个实体上最多只能使用一次。

    示例

    using System;
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
    public class AuthorAttribute: Attribute
    { 
       private string name;
       public AuthorAttribute(string name) {
          this.name = name;
       }
       public string Name { 
          get { return name; } 
       }
    }

    定义了一个名为 AuthorAttribute 的多次性属性类。示例

    [Author("Brian Kernighan"), Author("Dennis Ritchie")] 
    class Class1
    {
       ...
    }

    显示了一个两次使用 Author 属性的类声明。

    AttributeUsage 具有另一个名为 Inherited 的命名参数,此参数指示在基类上指定该属性时,该属性是否也会被从此基类派生的类所继承。如果属性类的 Inherited 为 true,则该属性会被继承。如果属性类的 Inherited 为 false 或者未指定,那么该属性不会被继承。

    没有附加 AttributeUsage 属性的属性类 X,例如

    using System;
    class X: Attribute {...}

    等效于下面的内容:

    using System;
    [AttributeUsage(
       AttributeTargets.All, 
       AllowMultiple = false, 
       Inherited = true)
    ]
    class X: Attribute {...}
  • 相关阅读:
    android 扇形菜单
    Gradle 教程:第一部分,安装【翻译】
    Android Studio 创建虚拟机失败 Failed to load 解决办法
    【翻译】Best Practices for User interface android 适配不同屏幕、不同分辨率
    [转]QT 4.8 静态库编译方法
    使用windows资源管理器打开jar
    一步步理解typedef
    模拟Chrome皮肤
    FAT12格式的引导区实现
    Android-获取Html元素
  • 原文地址:https://www.cnblogs.com/scottpei/p/2679926.html
Copyright © 2020-2023  润新知