码迷,mamicode.com
首页 > Windows程序 > 详细

C#中的Attribute属性

时间:2015-05-04 23:39:23      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:

       在C#中,attribute是作为一种程序源代码的元素修饰符存在的,因为有的时候我们需要给自己的代码添加一些描述性的说明信息。当这些我们不愿意用注释或内部代码用来描述的信息,被作为attribute代码而编译的话,编译器会将它们生成到metadata中去。

      同时,attribute也是一种object。

 1 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | 
 2 AttributeTargets.ReturnValue | AttributeTargets.Property, AllowMultiple = true, Inherited = true)] 
 3     public class CountryAttribute : Attribute
 4    { 
 5        
 6         public CountryAttribute(){} 
 7 
 8         public CountryAttribute(string name)
 9         { 
10             this.Name = name;         
11         } 
12 
13         public int PlayerCount { get; set; }         
14         public string Name { get; set; }     
15     } 
16 
17     [Country("China")]     
18     [Country("America")]     
19     public class Sportsman
20     { 
21         public string Name { get; set; }    
22      
23         [Country(PlayerCount = 5)]         
24         public virtual void Play(){}     
25      } 
26     
27     public class Hoopster : Sportsman     
28     { 
29         public override void Play(){}     
30      } 

        使用attribute有很显著的方便。他是一种会被编译的程序,但却能像注释一样使用。比起使用注释,attribute可以在执行结果中标识函数、返回值等结果,实现一些更加复杂的标识功能。但是,根据一些资料attribute本身并不是修饰符,而是一种类,被实例化的类,通过反编译可以看到这一点。

C#中的Attribute属性

标签:

原文地址:http://www.cnblogs.com/Dukechris/p/4477722.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!