正如msdn中所描述的那样-----“特性是被指定给某一声明的一则附加的声明性信息。”
使用预定义(pre-defined)特性
在c#中,有一个小的预定义特性集合。在学习如何建立我们自己的定制特性(custom 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特性,它标记了一个不应该再被使用的程序实体。第一个参数是一个字符串,它解释了为什么该实体是过时的以及应该用什么实体来代替它。实际上,你可以在这里写任何文本。第二个参数告诉编译器应该把使用这个过时的程序实体当作一种错误。它的默认值是false,也就是说编译器对此会产生一个警告。
当我们尝试编译上面这段程序的时候,我们将会得到一个错误:
anyclass.old()' is obsolete: 'don't use old method, use new method'
开发定制特性(custom attributes)
现在让我们来看看如何开发我们自己的特性。
首先我们要从system.attribute派生出我们自己的特性类(一个从system.attribute抽象类继承而来的类,不管是直接还是间接继承,都会成为一个特性类。特性类的声明定义了一种可以被放置在声明之上新的特性)。
using system;
public class helpattribute : attribute
{
}
不管你是否相信,我们已经建立了一个定制特性,现在我们可以用它来装饰现有的类就好像上面我们使用obsolete attribute一样。
[help()]
public class anyclass
{
}
注意:对一个特性类名使用attribute后缀是一个惯例。然而,当我们把特性添加到一个程序实体,是否包括attribute后缀是我们的自由。编译器会首先在system.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
{
}
在上面的例子中,我们给helpattribute特性类添加了一个属性并且在后续的部分中我们会在运行时环境中查寻它。
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器