C#特性(Attribute)入门(二)

文章作者 100test 发表时间 2007:05:12 12:14:25
来源 100Test.Com百考试题网


计算机等级考试训练软件《百宝箱》


定义或控制特性的使用

AttributeUsage类是另外一个预定义特性类,它帮助我们控制我们自己的定制特性的使用。它描述了一个定制特性如和被使用。

AttributeUsage有三个属性,我们可以把它放置在定制属性前面。第一个属性是:

ValidOn

通过这个属性,我们能够定义定制特性应该在何种程序实体前放置。一个属性可以被放置的所有程序实体在AttributeTargets enumerator中列出。通过OR操作我们可以把若干个AttributeTargets值组合起来。

AllowMultiple

这个属性标记了我们的定制特性能否被重复放置在同一个程序实体前多次。

Inherited

我们可以使用这个属性来控制定制特性的继承规则。它标记了我们的特性能否被继承。

下面让我们来做一些实际的东西。我们将会在刚才的Help特性前放置AttributeUsage特性以期待在它的帮助下控制Help特性的使用。

using System.
[AttributeUsage(AttributeTargets.Class), AllowMultiple = false,
Inherited = false ]
public class HelpAttribute : Attribute
{
public HelpAttribute(String Description_in)
{
this.description = Description_in.
}
protected String description.
public String Description
{
get
{
return this.description.
}
}
}
先让我们来看一下AttributeTargets.Class。它规定了Help特性只能被放在class的前面。这也就意味着下面的代码将会产生错误:

[Help("this is a do-nothing class")]
public class AnyClass
{
[Help("this is a do-nothing method")] //error
public void AnyMethod()
{
}
}
编译器报告错误如下:

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

It is valid on class declarations only.

我们可以使用AttributeTargets.All来允许Help特性被放置在任何程序实体前。可能的值是:

Assembly,
Module,
Class,
Struct,
Enum,
Constructor,
Method,
Property,
Field,
Event,
Interface,
Parameter,
Delegate,
All = Assembly | Module | Class | Struct | Enum | Constructor | Method | Property | Field | Event | Interface | Parameter | Delegate,
ClassMembers = Class | Struct | Enum | Constructor | Method | Property | Field | Event | Delegate | Interface )

相关文章


VFP中调用Oracle的存储过程
让VFP程序在浏览器中运行
C#特性(Attribute)入门(一)
如何提高VFP应用软件的路径适应性
C#特性(Attribute)入门(二)
用C#实现的数据加密(二)——哈希算法
用C#实现的数据加密(一)——对称加密算法
Office2007中快速输入各种特殊符号
做好使用Office2007的准备
澳大利亚华人论坛
考好网
日本华人论坛
华人移民留学论坛
英国华人论坛