C# Attributes:定义设计期信息

开发 后端
C# Attributes是一种新的描述信息,在这篇指南中我们将明白怎么创建属性并将其绑定至各种语言元素上,另外我们怎样在运行时环境下获取到attributes的一些信息。

约定:

     1.”attribute”和”attributes”均不翻译

     2.”property”译为“属性”

     3. msdn中的原句不翻译

     4.”program entity”译为”语言元素”

C# Attributes介绍

Attributes是一种新的描述信息,我们既可以使用attributes来定义设计期信息(例如 帮助文件,文档的URL),还可以用attributes定义运行时信息(例如,使XML中的元素与类的成员字段关联起来)。我们也可以用attributes来创建一个“自描述”的组件。

C# Attributes定义

MSDN 中做如下定义(ms-help://MS.MSDNQTR.2002APR.1033/csspec/html/vclrfcsharpspec_17_2.htm)

"An attribute is a piece of additional declarative information that is specified for a declaration." 

使用预定义 Attributes

在c#中已有一小组预定义的attributes,在我们学习怎样创建自定义attributes前,先来了解下在我们的代码中使用那些预定义的attributes.

  1. using System;  
  2.  
  3. public class AnyClass   
  4.  
  5. {  
  6.     [Obsolete("Don't use Old method, use New method"true)]  
  7.  
  8.     static void Old( ) { }  
  9.  
  10.     static void New( ) { }  
  11.  
  12.     public static void Main( )   
  13.     {  
  14.         Old( );  
  15.     }  
  16. }  
  17.  

仔细看下该实例,在该实例中我们用到了”Obsolete”attribute,它标记了一个不该再被使用的语言元素(译者注:这里的元素为方法),该属性的***个参数是string类型,它解释为什么该元素被荒弃,以及我们该使用什么元素来代替它。实际中,我们可以书写任何其它文本来代替这段文本。第二个参数是告诉编译器把依然使用这被标识的元素视为一种错误,这就意味着编译器会因此而产生一个警告。

当我们试图编译上面的上面的程序,我们会得到如下错误:

AnyClass.Old()' is obsolete: 'Don't use Old method,  use New method'

开发自定义Attributes

现在我们即将了解怎么开发自定义的attributes。这儿有个小小处方,有它我们就可以学会创建自定义的attributes。

在C#中,我们的attribute类都派生于System.Attribute类 (A class that derives from the abstract class System.Attribute, whether directly or indirectly, is an attribute class. The declaration of an attribute class defines a new kind of attribute that can be placed on a declaration) ,我们就这么行动吧。

  1. using System;  
  2.  
  3. public class HelpAttribute : Attribute  
  4.  
  5. {  
  6.  
  7. }  

不管你是否相信我,就这样我们就已经创建了一个自定义attribute。现在就可以用它来装饰我们的类了,就像我们使用obsolete attribute一样。

  1. [Help()]  
  2.  
  3. public class AnyClass  
  4.  
  5. {  
  6.  
  7. }  

注意:按惯例我们是用”Attribute“作为attribute类名的后缀,然而,当我们当我们把attribute绑定到某语言元素时,是不包含“Attribute“后缀的。编译器首先在System.Attribute 的继承类中查找该attribute,如果没有找到,编译器会把“Attribute“追加到该attribute的名字后面,然后查找它。

但是迄今为止,该attribute没有任何用处。为了使它有点用处,让我们在它里面加点东西吧。

  1. using System;  
  2. public class HelpAttribute : Attribute  
  3. {  
  4.     public HelpAttribute(String Descrition_in)  
  5.     {  
  6.         this.description = Description_in;  
  7.     }  
  8.     protected String description;  
  9.     public String Description   
  10.     {  
  11.         get   
  12.         {  
  13.             return this.description;  
  14.                    
  15.         }              
  16.     }      
  17. }  
  18. [Help("this is a do-nothing class")]  
  19. public class AnyClass  
  20. {  
  21. }  
  22.  

在上面的例子中,我们在attribute类中添加了一个属性,在***一节中,我们将在运行时查询该属性。

定义或控制自定义Attribute的用法

AttributeUsage 类是另一预定义类(译者注:attribute类本身用这个atrribute System.AttributeUsage来标记),它将帮助我们控制我们自定义attribute的用法,这就是,我们能为自定义的attribute类定义attributes。

它描述了一个自定义attribute类能被怎样使用。

AttributeUsage 提供三个属性,我们能将它们放置到我们的自定义attribute类上, ***个特性是:

ValidOn

通过这个属性,我们能指定我们的自定义attribute可以放置在哪些语言元素之上。这组我们能把自定义attribute类放置其上的语言元素被放在枚举器AttributeTargets 中。我们可以使用bitwise(译者注:这个词不知道怎么翻译好,但他的意思是可以这么用:[AttributeUsage((AttributeTargets)4, AllowMultiple = false, Inherited = false )],4代表就是“class”元素,其它诸如1代表“assembly”,16383代表“all”等等)或者”.”操做符绑定几个AttributeTargets 值。(译者注:默认值为AttributeTargets.All)

AllowMultiple

该属性标识我们的自定义attribte能在同一语言元素上使用多次。(译者注:该属性为bool类型,默认值为false,意思就是该自定义attribute在同一语言元素上只能使用一次)

Inherited

我们可以使用该属性来控制我们的自定义attribute类的继承规则。该属性标识我们的自定义attribute是否可以由派生类继承。((译者注:该属性为bool类型,默认值为false,意思是不能继承)

让我们来做点实际的东西吧,我们将把AttributeUsage attribute 放置在我们的help attribute 上并在它的帮助下,我们来控制help attribute的用法。

  1. using System;  
  2.  
  3. [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false )]  
  4.  
  5. public class HelpAttribute : Attribute  
  6.  
  7. {  
  8.  
  9.     public HelpAttribute(String Description_in)  
  10.  
  11.     {  
  12.  
  13.         this.description = Description_in;  
  14.  
  15.     }  
  16.  
  17.     protected String description;  
  18.  
  19.     public String Description  
  20.  
  21.     {  
  22.  
  23.         get   
  24.  
  25.         {  
  26.  
  27.             return this.description;  
  28.  
  29.         }              
  30.  
  31.     }      
  32.  
  33. }  
  34.  

首先我们注意 AttributeTargets.Class. 它规定这个help attribute 只能放置在语言元素”class”之上。这就意味着,下面的代码将会产生一个错误。

AnyClass.cs: Attribute 'Help' is not valid on this declaration type.

It is valid on 'class' declarations only.

现在试着把它绑定到方法。

  1. [Help("this is a do-nothing class")]  
  2.  
  3. public class AnyClass  
  4.  
  5. {  
  6.  
  7.     [Help("this is a do-nothing method")]    //error  
  8.  
  9.     public void AnyMethod()  
  10.  
  11.     {  
  12.  
  13.     }  
  14.  
  15. }   
  16.  

我们可以使用 AttributeTargets.All 来允许 Help attribute 可以放置在任何预定义的语言元素上,那些可能的语言元素如下: 

可能的语言元素 

  1. [Help("this is a do-nothing class")]  
  2.  
  3. [Help("it contains a do-nothing method")]  
  4.  
  5. public class AnyClass  
  6.  
  7. {  
  8.  
  9.     [Help("this is a do-nothing method")]        //error  
  10.  
  11.     public void AnyMethod()  
  12.  
  13.     {  
  14.  
  15.     }  
  16.  
  17. }  

它产生了一个编译错误:

AnyClass.cs: Duplicate 'Help' attribute

Ok!现在我们该讨论下***那个属性了,”Inherited”, 指出当把该attribute放置于一个基类之上,是否派生类也继承了该attribute。如果绑定至某个attribute类的”Inherited”被设为true,那么该attribute就会被继承,然而如果绑定至某个attribute类的”Inherited”被设为false或者没有定义,那么该attribute就不会被继承。

让我们假设有如下的类关系。

  1. [Help("BaseClass")]   
  2.  
  3. public class Base  
  4.  
  5. {  
  6.  
  7. }  
  8.  
  9.    
  10.  
  11. public class Derive :  Base  
  12.  
  13. {  
  14.  
  15. }  
  16.  

我们有四种可能的绑定:

四种可能的绑定 

***种情况

如果我们查询(我们将在后面来了解如何在运行时来查询attributes)派生类中的help attribute,我们将不可能查询到因为”Inherited”被设为了false。

第二种情况

第二种情况没有什么不同,因为其”Inherited”也被设为了false。

第三种情况

为了解释第三种和第四种情况,让我们为派生类也绑定同一attribute。

  1. [Help("BaseClass")]   
  2.  
  3. public class Base  
  4.  
  5. {  
  6.  
  7. }  
  8.  
  9. [Help("DeriveClass")]   
  10.  
  11. public class Derive :  Base  
  12.  
  13. {  
  14.  
  15. }  
  16.  

现在我们查询相关的help attribute ,我们将仅仅可以得到派生类的attribute,为什么这样是因为help attribute虽然允许被继承,但不能多次在同一语言元素上使用,所以基类中的help attribute被派生类的help attribute 重写了。

第四种情况

在第四种情况中,当我们查询派生类的help attribute 时,我们可以得到两个attributes,当然是因为help attribute既允许被继承,又允许在同一语言元素上多次使用的结果。

注意:AttributeUsage attribute 仅应用在那种是System.Attribute 派生的attriubte类而且绑定值该attriubte类的AllowMultiple和Inherited均为false上才是有效的。

可选参数 vs. 命名参数

可选参数是attribute类构造函数的参数。它们是强制的,必须在每次在attribute绑定至某语言元素时提供一个值。而另一方面,命名参数倒是真正的可选参数,不是在attribute构造函数的参数。

为了更加详细的解释,让我们在Help类中添加另外的属性。

  1. [AttributeUsage(AttributeTargets.Class, AllowMultiple = false,  
  2.  
  3.  Inherited = false)]  
  4.  
  5. public class HelpAttribute : Attribute  
  6.  
  7. {  
  8.  
  9.     public HelpAttribute(String Description_in)  
  10.  
  11.     {  
  12.  
  13.         this.description = Description_in;  
  14.  
  15.         this.verion = "No Version is defined for this class";  
  16.  
  17.     }  
  18.  
  19.     protected String description;  
  20.  
  21.     public String Description  
  22.  
  23.     {  
  24.  
  25.         get   
  26.  
  27.         {  
  28.  
  29.             return this.description;  
  30.  
  31.         }  
  32.  
  33.     }  
  34.  
  35.     protected String version;  
  36.  
  37.     public String Version  
  38.  
  39.     {  
  40.  
  41.         get   
  42.  
  43.         {  
  44.  
  45.             return this.version;  
  46.  
  47.         }  
  48.  
  49.         //if we ever want our attribute user to set this property,   
  50.  
  51.         //we must specify set method for it   
  52.  
  53.         set   
  54.  
  55.         {  
  56.  
  57.             this.verion = value;  
  58.  
  59.         }  
  60.  
  61.     }  
  62.  
  63. }  
  64.  
  65. [Help("This is Class1")]  
  66.  
  67. public class Class1  
  68.  
  69. {  
  70.  
  71. }  
  72.  
  73.  
  74.  
  75. [Help("This is Class2", Version = "1.0")]  
  76.  
  77. public class Class2  
  78.  
  79. {  
  80.  
  81. }  
  82.  
  83.  
  84.  
  85. [Help("This is Class3", Version = "2.0",   
  86.  
  87.  Description = "This is do-nothing class")]  
  88.  
  89. public class Class3  
  90.  
  91. {  
  92.  
  93. }  
  94.  

当我们在Class1中查询Help attribute已经它的属性,我们将得到:

Help.Description : This is Class1

Help.Version :No Version is defined for this class

因为我们没有为Version这个属性定义任何任何值,所以在构造函数中设定的值被我们查询出来了。如果没有定义任何值,那么就会赋一个该类型的默认值(例如:如果是int型,默认值就是0)。

现在,查询Class2的结果是:

Help.Description : This is Class2

Help.Version :  1.0

我们不能为了可选参数而使用多个构造函数,应该用已命名参数来代替。我们之所以称它们为已命名的,是因为当我们在构造函数为它们提供值时,我们必须命名它们。例如,在第二个类中,我们如是定义Help。

[Help("This is Class2", Version = "1.0")]

在 AttributeUsage 例子中, 参数”ValidOn”是可选参数,而“Inherited“和“AllowMultiple“ 是命名参数。

注意:为了在attribute的构造函数中设定命名参数的值,我们必须为相应的属性提供一个set方法否则会引起编译期错误:

'Version' : Named attribute argument can't be a read only property

现在,我们在Class3中查找Help attribute 及其属性会发生什么呢?结果是跟上面提到的相同的编译期错误。

'Desciption' : Named attribute argument can't be a read only property

现在我们修改下Help类,为属性”Description”加一个set方法。现在的输出就是:

Help.Description : This is do-nothing class

Help.Version : 2.0

在屏幕后面究竟发生了什么呢?首先带有可选参数的构造函数被调用,然后,每个命名参数的set方法被调用,在构造函数中赋给命名参数的值被set方法所覆写。

参数类型

一个attribute类的参数类型被限定在如下类型中:

attribute类的参数类型  

Attributes 标记

假设,我们想把Help attribute 绑定至元素 assembly。***个问题是我们要把Help attribute 放在哪儿才能让编译器确定该attribute是绑定至整个assembly呢?考虑另一种情况,我们想把attribute绑定至一个方法的返回类型上,怎样才能让编译器确定我们是把attribute绑定至方法的返回类型上,而不是整个方法呢?

为了解决诸如此类的含糊问题,我们使用attribute标识符,有了它的帮助,我们就可以确切地申明我们把attribute 绑定至哪一个语言元素。

例如:

[assembly: Help("this a do-nothing assembly")]

这个在Help attribute 前的assembly标识符确切地告诉编译器,该attribute被绑定至整个assembly。可能的标识符有: 

可能的标识符 

在运行时查询Attributes

现在我们明白怎么创建attribtes和把它们绑定至语言元素。是时候来学习类的使用者该如何在运行时查询这信息。

为了查询一语言元素上绑定的attributes,我们必须使用反射。反射有能力在运行时发现类型信息。

我们可以使用.NET Framework Reflection APIs 通过对整个assembly元数据的迭代,列举出assembly中所有已定义的类,类型,还有方法。

记住那旧的Help attribute 和AnyClass 类。

  1. using System;  
  2.  
  3. using System.Reflection;  
  4.  
  5. using System.Diagnostics;  
  6.  
  7.  
  8.  
  9. //attaching Help attribute to entire assembly  
  10.  
  11. [assembly : Help("This Assembly demonstrates custom attributes   
  12.  
  13.  creation and their run-time query.")]  
  14.  
  15.  
  16.  
  17. //our custom attribute class  
  18.  
  19. public class HelpAttribute : Attribute  
  20.  
  21. {  
  22.  
  23.     public HelpAttribute(String Description_in)  
  24.  
  25.     {  
  26.  
  27.         //  
  28.  
  29.         // TODO: Add constructor logic here  
  30.  
  31.         this.description = Description_in;  
  32.  
  33.         //  
  34.  
  35.     }  
  36.  
  37.     protected String description;  
  38.  
  39.     public String Description  
  40.  
  41.     {  
  42.  
  43.         get   
  44.  
  45.         {  
  46.  
  47.             return this.deescription;  
  48.  
  49.                    
  50.  
  51.         }              
  52.  
  53.     }      
  54.  
  55. }  
  56.  
  57. //attaching Help attribute to our AnyClass  
  58.  
  59. [HelpString("This is a do-nothing Class.")]  
  60.  
  61. public class AnyClass  
  62.  
  63. {  
  64.  
  65. //attaching Help attribute to our AnyMethod  
  66.  
  67.     [Help("This is a do-nothing Method.")]  
  68.  
  69.     public void AnyMethod()  
  70.  
  71.     {  
  72.  
  73.     }  
  74.  
  75. //attaching Help attribute to our AnyInt Field  
  76.  
  77.     [Help("This is any Integer.")]  
  78.  
  79.     public int AnyInt;  
  80.  
  81. }  
  82.  
  83. class QueryApp  
  84.  
  85. {  
  86.  
  87.     public static void Main()  
  88.  
  89.     {  
  90.  
  91.     }  
  92.  
  93. }  
  94.  

我们将在接下来的两节中在我们的Main方法中加入attribute查询代码。

查询程序集的Attributes

在接下来的代码中,我们先得到当前的进程名称,然后用Assembly类中的LoadForm()方法加载程序集,再有用GetCustomAttributes()方法得到被绑定至当前程序集的自定义attributes,接下来用foreach语句遍历所有attributes并试图把每个attribute转型为Help attribute(即将转型的对象使用as关键字有一个优点,就是当转型不合法时,我们将不需担心会抛出异常,代之以空值(null)作为结果),接下来的一行就是检查转型是否有效,及是不是为空,跟着就显示Help attribute的“Description”属性。

  1. class QueryApp  
  2.  
  3. {  
  4.  
  5.     public static void Main()  
  6.  
  7.     {  
  8.  
  9.         HelpAttribute HelpAttr;  
  10.  
  11.  
  12.         //Querying Assembly Attributes  
  13.  
  14.         String assemblyName;  
  15.  
  16.         Process p = Process.GetCurrentProcess();  
  17.  
  18.         assemblyName = p.ProcessName + ".exe";  
  19.  
  20.  
  21.         Assembly a = Assembly.LoadFrom(assemblyName);  
  22.  
  23.  
  24.         foreach (Attribute attr in a.GetCustomAttributes(true))  
  25.         {  
  26.  
  27.             HelpAttr = attr as HelpAttribute;  
  28.  
  29.             if (null != HelpAttr)  
  30.  
  31.             {  
  32.  
  33.                 Console.WriteLine("Description of {0}:\n{1}",   
  34.  
  35.                                   assemblyName,HelpAttr.Description);  
  36.  
  37.             }  
  38.  
  39.         }  
  40.  
  41. }  
  42.  
  43. }  
  44.  

程序输出如下:

Description of QueryAttribute.exe:

This Assembly demonstrates custom attributes creation and

their run-time query.

Press any key to continue

查询类、方法、类成员的Attributes

下面的代码中,我们惟一不熟悉的就是Main()方法中的***行。

Type type = typeof(AnyClass);

它用typeof操作符得到了一个与我们AnyClass类相关联的Type型对象。剩下的查询类attributes代码就与上面的例子是相似的,应该不要解释了吧(我是这么想的)。

为查询方法和类成员的attributes,首先我们得到所有在类中存在的方法和成员,然后我们查询与它们相关的所有attributes,这就跟我们查询类attributes一样的方式。

  1. class QueryApp  
  2.  
  3. {  
  4.  
  5.     public static void Main()  
  6.  
  7.     {  
  8.  
  9.  
  10.  
  11.         Type type = typeof(AnyClass);  
  12.  
  13.         HelpAttribute HelpAttr;  
  14.  
  15.  
  16.  
  17.  
  18.  
  19.         //Querying Class Attributes  
  20.  
  21.         foreach (Attribute attr in type.GetCustomAttributes(true))  
  22.  
  23.         {  
  24.  
  25.             HelpAttr = attr as HelpAttribute;  
  26.  
  27.             if (null != HelpAttr)  
  28.  
  29.             {  
  30.  
  31.                 Console.WriteLine("Description of AnyClass:\n{0}",   
  32.  
  33.                                   HelpAttr.Description);  
  34.  
  35.             }  
  36.  
  37.         }  
  38.  
  39.         //Querying Class-Method Attributes    
  40.  
  41.         foreach(MethodInfo method in type.GetMethods())  
  42.  
  43.         {  
  44.  
  45.             foreach (Attribute attr in method.GetCustomAttributes(true))  
  46.  
  47.             {  
  48.  
  49.                 HelpAttr = attr as HelpAttribute;  
  50.  
  51.                 if (null != HelpAttr)  
  52.  
  53.                 {  
  54.  
  55.                     Console.WriteLine("Description of {0}:\n{1}",   
  56.  
  57.                                       method.Name,   
  58.  
  59.                                       HelpAttr.Description);  
  60.  
  61.                 }  
  62.  
  63.             }  
  64.  
  65.         }  
  66.  
  67.         //Querying Class-Field (only public) Attributes  
  68.  
  69.         foreach(FieldInfo field in type.GetFields())  
  70.  
  71.         {  
  72.  
  73.             foreach (Attribute attr in field.GetCustomAttributes(true))  
  74.  
  75.             {  
  76.  
  77.                 HelpAttr= attr as HelpAttribute;  
  78.  
  79.                 if (null != HelpAttr)  
  80.  
  81.                 {  
  82.  
  83.                     Console.WriteLine("Description of {0}:\n{1}",  
  84.  
  85.                                       field.Name,HelpAttr.Description);  
  86.  
  87.                 }  
  88.  
  89.             }  
  90.  
  91.         }  
  92.  
  93.     }  
  94.  
  95. }  
  96.  

以上就介绍了C# Attributes的一些使用方法。

【编辑推荐】

责任编辑:book05 来源: cnblogs
相关推荐

2009-08-07 17:57:26

C#定义事件应用

2009-08-03 18:26:18

C#定义接口成员

2009-08-10 14:55:04

C#定义Nullabl

2009-08-27 17:59:56

C#接口定义

2009-08-31 16:47:39

C#接口的定义

2009-08-07 13:39:13

C#定义整型数组

2009-08-25 16:24:44

C#信息架构视图

2009-08-26 10:24:04

C# Observer

2009-08-04 08:58:01

C#自定义特性

2009-09-02 16:30:20

C#定义数组

2009-08-25 10:44:08

C#接口定义接口

2009-08-18 17:51:17

C#实现Interne

2009-09-07 06:07:46

C#窗体设计

2009-09-28 14:45:22

C#接口的定义

2009-09-10 17:48:05

C# button

2009-09-24 15:20:54

C#接口定义

2009-08-12 15:55:12

C#接口定义

2009-08-13 14:46:03

C#结构体定义

2009-09-02 17:53:42

C#程序设计Windows窗体

2009-09-02 16:23:27

C# Singleto
点赞
收藏

51CTO技术栈公众号