24.2.3 访问特性

万事俱备只欠东风。我们已经有了自定义的特性,并且已经给实体类应用了特性,那么该怎么使用特性提供的这些附加信息呢?接下来,我们会使用第24.1节的元数据知识,使用反射技术将这些信息在运行时提取出来,并加以利用。代码清单24-20仅仅将提取出的特性信息输出到控制台,作为示例之用。

代码清单24-20 访问特性


class AttributeSample

{

public static void Main(string[]args)

{

Book book=new Book();

//获得book对象的Type实例

Type type=book.GetType();

//获得应用于Book类的TableAttribute特性

TableAttribute tableAttribute=(TableAttribute)type.GetCustomAttributes(false)[0];

//类型的名称

Console.WriteLine("Class:{0}",type.Name);

//特性的名称

Console.WriteLine("table={0}",tableAttribute.Name);

//获取PropertyInfo实例(属性)数组

PropertyInfo[]infos=type.GetProperties();

//遍历infos数组

foreach(PropertyInfo prop in infos)

{

//获取定义于每个属性之上的特性数组

object[]attributes=prop.GetCustomAttributes(false);

Console.Write("-".PadRight(80,'-'));

//属性名

System.Console.WriteLine("Property:{0}",prop.Name);

//遍历特性数组

foreach(Attribute attribute in attributes)

{

//如果是ColumnAttribute特性

if(attribute is ColumnAttribute)

{

//类型转换

ColumnAttribute columnAttribute=attribute as ColumnAttribute;

//特性的ColumnName属性

string columnName=columnAttribute.ColumnName;

//特性的ColumnType属性

string columnType=columnAttribute.ColumnType;

//特性的ColumnLength属性

int columnLength=columnAttribute.ColumnLength;

//特性的IsNull属性

bool columnIsNull=columnAttribute.IsNull;

Console.WriteLine("columnName={0},columnType={1},columnLength={2},columnIsNull={3}",columnName,columnType,

columnLength,columnIsNull);

}

}

}

}

}