§ ITPOW >> 文档 >> C#

C# 中的特性(Attributes)-1

作者:子非鱼 来源:子非鱼的 blog 日期:2009-1-31

英文原文:http://www.codeproject.com/KB/cs/attributes.aspx

约定

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

     2.”property”译为“属性”

     3.msdn中的原句不翻译

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

Attributes in C#

介绍

Attributes是一种新的描述信息,我们既可以使用attributes来定义设计期信息(例如 帮助文件,文档的URL),还可以用attributes定义运行时信息(例如,使XML中的元素与类的成员字段关联起来)。我们也可以用attributes来创建一个“自描述”的组件。在这篇指南中我们将明白怎么创建属性并将其绑定至各种语言元素上,另外我们怎样在运行时环境下获取到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.

using System;
 
public class AnyClass
{
    [Obsolete("Don't use Old method, use New method", true)]
    static void Old( ) { }
   
    static void New( ) { }
   
    public static void Main( )
    {
        Old( );
    }
}

仔细看下该实例,在该实例中我们用到了”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) ,我们就这么行动吧。

using System;
 
public class HelpAttribute : Attribute
{
 
}

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

[Help()]
public class AnyClass
{
 
}

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

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

using System;
public class HelpAttribute : Attribute
{
    public HelpAttribute(String Descrition_in)
    {
        this.description = Description_in;
    }
    protected String description;
    public String Description
    {
        get
        {
            return this.description;
        }
    }
}

[Help("this is a do-nothing class")]
public class AnyClass
{
}

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

相关文章