C#中的Attribute属性

       在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 { getset; }         
14         public string Name { getset; }     
15 16 
17     [Country("China")]     
18     [Country("America")]     
19     public class Sportsman
20 21         public string Name { getset; }    
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本身并不是修饰符,而是一种类,被实例化的类,通过反编译可以看到这一点。

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