博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[AttributeUsage(AttributeTargets.Class)] 用法例子
阅读量:6901 次
发布时间:2019-06-27

本文共 1900 字,大约阅读时间需要 6 分钟。

首先,创建一个自定义的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!************/
/***********************************/
 
 

转载于:https://www.cnblogs.com/ruingking/p/10247487.html

你可能感兴趣的文章
用 MuGo 搭建 Go Engine 在 KGS 对战
查看>>
第二篇*2、Python字符串格式化
查看>>
正则表达式以过滤特殊字符
查看>>
关于bootstrap
查看>>
【DM642】H.264源代码在DM642上的移植
查看>>
清晰化算法在DSP上的实现
查看>>
图的存储结构(邻接矩阵)
查看>>
Delphi7_Lite_Fullv7.3优化精简全功能版
查看>>
Android笔记之自定义对话框
查看>>
【转】超实用的JavaScript技巧及最佳实践
查看>>
EIGRP高级特性(汇总,偏移列表,SIA,Stub)
查看>>
C# 格式化新招
查看>>
sql server中的left, right, substring在oracle中都用substr实现
查看>>
Hackthissite realistic 11解密题后的记录
查看>>
编程之美 第1章 游戏之乐——游戏中碰到的题目(二)
查看>>
一种循环方式
查看>>
ChartControl第一课简短的控件初步设计
查看>>
个人博客作业三:微软小娜APP的案例分析
查看>>
python-玉米(小米)商城作业
查看>>
游戏超写实贴图制作技巧
查看>>