首先,創建一個自定義的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,以及如何在應用程序使用它.