• [AttributeUsage(AttributeTargets.Class)] 用法例子


    首先,创建一个自定义的Attribute,并且事先设定我们的Attribute将施加在class的元素上面以获取一个类代码的检查信息。
    复制代码
    using System;
    using System.Reflection; 
    [AttributeUsage(AttributeTargets.Class)]
    public class CodeReviewAttribute : System.Attribute //定义一个CodeReview的Attribute
    {
     private string reviewer;  //代码检查人
     private string date;      //检查日期
     private string comment;   //检查结果信息
     //参数构造器
     public CodeReviewAttribute(string reviewer, string date)
     {
      this.reviewer=reviewer;
      this.date=date;
     }
     public string Reviewer
     {
      get
      {
       return reviewer;
      }
     }
     public string Date
     {
      get
      {
       return date;
      }
     }
     public string Comment
     {
      get
      {
       return comment;
      }
      set
      {
       comment=value;
      }
     }
    }
    复制代码


    自定义CodeReviewAttribute同普通的类没有区别,它从Attribute派生,同时通过AttributeUsage表示我们的Attribute仅可以施加到类元素上。
    第二步就是使用我们的CodeReviewAttribute, 假如有一个Jack写的类MyClass,检查人Niwalker,检查日期2003年7月9日,于是我们施加Attribute如下:
    [CodeReview("Niwalker","2003-7-9",Comment="Jack的代码")]
    public class MyClass
    {
     //类的成员定义
    }

    当这段代码被编译的时候,编译器会调用CodeReviewAttribute的构造器并且把"Niwalker"和"2003-7-9"分别作为构造器的参数。注意到参数表中还有一个Comment属性的赋值,这是Attribute特有的方式,这里可以设置更多的Attribute的公共属性(如果有的话),需要指出的是.NET Framework1.0允许向private的属性赋值
    但在.NET Framework1.1已经不允许这样做,只能向public的属性赋值。
    第三步就是取出需要的信息,这是通过.NET的反射来实现的:
    复制代码
    class test
    {
       static void Main(string[] args)
       {
          System.Reflection.MemberInfo info=typeof(MyClass); //通过反射得到MyClass类的信息
    //得到施加在MyClass类上的定制Attribute
          CodeReviewAttribute att=
                    (CodeReviewAttribute)Attribute.GetCustomAttribute(info,typeof(CodeReviewAttribute));
          if(att!=null)
          {
              Console.WriteLine("代码检查人:{0}",att.Reviewer);
              Console.WriteLine("检查时间:{0}",att.Date);
              Console.WriteLine("注释:{0}",att.Comment);
          }
       }
    }
    复制代码
    在上面这个例子中,Attribute扮演着向一个类添加额外信息的角色,它并不影响MyClass类的行为。
    通过这个例子,可以知道如何写一个自定义的Attribute,以及如何在应用程序使用它.
    /***********************************/
    /***********Hello!world!************/
    /***********************************/
     
  • 相关阅读:
    小程序裁剪图片上传头像,二维码源码
    算法随笔
    背景色根据数值由深到浅
    jquery 点击弹框
    css3
    HTML5中手势原理分析与数学知识的实践
    es6(var,let,const,set,map,Array.from())
    taro3.0 Swiper album example
    taro3.x: 搭建redux环境
    taro: fial cannot navigate back at first page
  • 原文地址:https://www.cnblogs.com/ruingking/p/10247487.html
Copyright © 2020-2023  润新知