反射需要一整本书来讨论,这里只介绍了Type类和Assembly类,他们是访问反射所提供的拓展功能的主要入口点。这里介绍了自定义特性,它比其它方面更常用,以及如何在运行期间检索自定义特性信息。
一、自定义特性
内置的特性可以根据特性来影响编译。
自定义特性可以在运行期间获取程序信息,可以影响执行程序的方式。例如自定义特性可以用于支持对自定义许可类进行声明性的代码访问
安全检查,把信息与程序元素关联起来,程序元素由测试工具使用,或者在开发可拓展的架构时允许加载插件和模块。
特性的使用:
编译器发现[FieldName("socialsecurityNumber")]时,会把字符串Attribute追加到这个名称后面,形成一个组合名称FieldNameAttribute
,然后搜索所在的名称空间(包括using的)搜索有指定名称的类。
自定义特性,继承自:Attribute
using System;
namespace WhatsNewAttributes
{
[AttributeUsage( // AttributeUsage是.net定义的特性的内置特性说明,可以叫特性的元特性。
AttributeTargets.Class | AttributeTargets.Method,// 应用到的程序元素[必选],使用时候如果是assembly或module的可以放
置在代码中的任何地方
AllowMultiple = true, // 同一个程序元素上是否可以使用多次[可选]
Inherited = false)] // 是否可以继承,接口/类,如果是属性方法那么重载属性方法中也会影响[可选]
public class LastModifiedAttribute : Attribute
{
private readonly DateTime _dateModified;
private readonly string _changes;
// 有两个必选参数
public LastModifiedAttribute(string dateModified, string changes)
{
_dateModified = DateTime.Parse(dateModified);
_changes = changes;
}
//没有set函数,是因为需要作为构造函数参数传入,不能内部指定。
public DateTime DateModified
{
get { return _dateModified; }
}
public string Changes
{
get { return _changes; }
}
// 这个属性为可选参数
public string Issues { get; set; }
}
[AttributeUsage(AttributeTargets.Assembly)]
public class SupportsWhatsNewAttribute : Attribute
{
}
}
二、实体类中使用特性
using System;
using System.Collections;
using System.Text;
using WhatsNewAttributes; // 引入特性定义类
// 声明该程序集使用全局的SupportsWhatsNewAttribute特性类
[assembly: SupportsWhatsNew]
namespace VectorClass
{
// 使用LastModifiedAttribute特性类
[LastModified("14 Feb 2010", "IEnumerable interface implemented " +
"So Vector can now be treated as a collection")]
[LastModified("10 Feb 2010", "IFormattable interface implemented " +