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的代码

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