C#-Attribute

Attribute是一種類似關鍵字的描述性聲明,傳統的編譯器只能識別預

定義的關鍵字,所有一般來說程序員沒有辦法定義自己的關鍵字,但是

有了Attribute了之後就可以用它來影響編譯器的行爲。

usingSystem;

namespace_06_04
{
    [Obsolete("
這是一個已經廢棄的類")]
    public class MyClass
    {
        [Obsolete("
已經廢棄的方法")]
        public void MyMethod()
        {
           Console.WriteLine("
已經廢棄的方法");
        }

       public void otherMethod()
        {
           Console.WriteLine("
沒有被標記的廢棄的方法");
        }
    }

   public class Class_06_04
    {
        public static void Main()
        {
            MyClass me =new MyClass();
           me.otherMethod();
           me.MyMethod();
           Console.ReadLine();
        }
    }
}

build是又警告顯示_06_04.MyClass是已經廢棄的類

由於Attribute可以把信息存儲在.NET程序集的元數據當中,這就使得

Attribute具有了描述代碼本身的能力。
Attribute
也是類繼承System.Attribute,我們也可以自己定義

Attribute.

usingSystem;
using System.Reflection;

namespace_06_04
{
    //
定義CodeAuthorAttribute,要求它只能施加於類
    [AttributeUsage(AttributeTargets.Class)]
    public class CodeAuthorAttribute : Attribute
    {
        public string Name;
        public DateTime Date;
        public string Comment;

       public CodeAuthorAttribute()
        {
            Date =DateTime.Now;
        }

       public CodeAuthorAttribute(string Name, string Date)
        {
            this.Name =Name;
            this.Date =DateTime.Parse(Date);       
        }
    }

   //CodeAuthorAttribute施加於3個類
    //
這裏用CodeAuthor(),是因爲Attribute類的名字一定要

"Attribute"結尾,使用的時候可以省略最後一個"Attribute"
    [CodeAuthor()]
    public class MyClass1
    { }

   [CodeAuthor("Fei", "2012-06-04")]
    public class MyClass2
    { }

   [CodeAuthor("Fei", "2012-06-04", Comment = "Fei的代碼")]
    public class MyClass3
    { }

   public class Class_06_04
    {
        public static void Main()
        {
            //
得到MyClass類的信息
            MemberInfo[]infos = new MemberInfo[3];
            infos[0] =typeof(MyClass1);
            infos[1] =typeof(MyClass2);
            infos[2] =typeof(MyClass3);

           foreach (MemberInfo info in infos)
            {
               //
得到CodeAuthor的實例,使用Attribute類的兩個靜

態方法GetCustomeAttribute(s)來檢索Attribute信息。
               CodeAuthorAttribute att =

(CodeAuthorAttribute)Attribute.GetCustomAttribute(info,
                   typeof(CodeAuthorAttribute));
               if (att != null)
               {
                   Console.WriteLine("
類名:{0}", info.Name);
                   Console.WriteLine("
作者:{0}", att.Name);
                   Console.WriteLine("
時間:{0}", att.Date);
                   Console.WriteLine("
說明:{0}",

att.Comment);
                   Console.WriteLine();
               }
               Console.ReadLine();
            }
        }
    }
}

輸出結果:
類名:MyClass1
作者:
時間:2012-06-0422:47:35
說明:

類名:MyClass2
作者:Fei
時間:2012-06-0422:47:35
說明:

類名:MyClass3
作者:Fei
時間:2012-06-0422:47:35
說明:Fei的代碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章