C#特性学习笔记二

实例探讨:

自定义了一个特性类:

 

[c-sharp] view plain copy print ?
  1. [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method)]  
  2. class WahAttribute:System.Attribute  
  3. {  
  4.     private string description;  
  5.   
  6.     public string Description  
  7.     {  
  8.         get { return description; }  
  9.         set { description = value; }  
  10.     }  
  11.     private string author;  
  12.   
  13.     public string Author  
  14.     {  
  15.         get { return author; }  
  16.         set { author = value; }  
  17.     }  
  18.     public WahAttribute(string desc)  
  19.     {  
  20.         this.description = desc;  
  21.     }  
  22. }  

 

运用特性类:

 

[c-sharp] view plain copy print ?
  1. namespace attributeDemo  
  2. {  
  3.     public class Teacher  
  4.     {  
  5.         private string name;  
  6.   
  7.         public string Name  
  8.         {  
  9.             get { return name; }  
  10.             set { name = value; }  
  11.         }  
  12.         private int age;  
  13.   
  14.         public int Age  
  15.         {  
  16.             get { return age; }  
  17.             set { age = value; }  
  18.         }  
  19.         private string sex;  
  20.   
  21.         public string Sex  
  22.         {  
  23.             get { return sex; }  
  24.             set { sex = value; }  
  25.         }  
  26.         //只有用户名为wah的才可以调用此方法  
  27.         [Wah("this is my attribute test", Author = "wah", Description = "test")]  
  28.         public string getMessage()  
  29.         {  
  30.             return "好好学习,天天向上";  
  31.         }  
  32.         [Wah("this is with parameters test",Author="wanggaihui",Description="test with parameters")]  
  33.         public int Test(int a,int b)  
  34.         {  
  35.             return a+b;  
  36.         }  
  37.     }  
  38. }  

 

处理特性类:

 

[c-sharp] view plain copy print ?
  1. private void button_Click(object sender, EventArgs e)  
  2. {  
  3.     //得到类型  
  4.     Type type = typeof(Teacher);  
  5.     //得到此类型所有方法  
  6.     MethodInfo[] methods = type.GetMethods();  
  7.     foreach (MethodInfo method in methods)  
  8.     {  
  9.         //得到此方法的所有特性  
  10.         object[] attributes = method.GetCustomAttributes(false);  
  11.         foreach (object o in attributes)  
  12.         {  
  13.             //判断是否是自己定义的特性  
  14.             if (o.GetType() == typeof(WahAttribute))  
  15.             {  
  16.                 //强转取得值  
  17.                 WahAttribute waha = (WahAttribute)o;  
  18.                 this.listBox1.Items.Add("author=" + waha.Author);  
  19.                 this.listBox1.Items.Add("description=" + waha.Description);  
  20.             }  
  21.         }  
  22.     }  
  23. }  

 

C#特性可以应用于各种类型和成员。加在类前面的是类特性,加在方法前面的是方法特性。无论他们被用在哪里,无论他们之间有什么区别,特性的最主要的目的就是自描述。并且因为特性是可以由自己定制的,而不仅仅局限于.net提供的那几个现成的,因此给C#程序开发带来了很大的灵活性。

你可能感兴趣的:(学习笔记)