C#反射技术之二读取Attribute特性。
前面的文章我已经给大家介绍了一下Attribute的基本知识,今天我打算介绍一下,如何利用反射技术来读取我们自定义的Attribute。
我们可以通过一个类的Type的GetCustomAttributes方法来读取这个类上所附加的特性。这个方法的具体用法在MSDN上已经说得很清楚,大家自己可以研究一下。
读取到类所对应的表的特性了,接下来我们该读取类里包含的属性上所附加的ColumAttribute特性了。
1 Type t;
Student instence = new Student();
2 type = instence.GetType();
3 tableName = (type.GetCustomAttributes(typeof(TalbeAttribute), false)[0] as TalbeAttribute).TableName;
4
这样我们就得到了实体类上所附加的TableAttribute特性类的TableName属性。Student instence = new Student();
2 type = instence.GetType();
3 tableName = (type.GetCustomAttributes(typeof(TalbeAttribute), false)[0] as TalbeAttribute).TableName;
4
我们可以通过一个类的Type的GetCustomAttributes方法来读取这个类上所附加的特性。这个方法的具体用法在MSDN上已经说得很清楚,大家自己可以研究一下。
读取到类所对应的表的特性了,接下来我们该读取类里包含的属性上所附加的ColumAttribute特性了。
private static PropertyInfo[] propInfos = null;
private static List<PropertyInfo> propPrimarys = new List<PropertyInfo>(); //保存主键列
private static List<PrimaryKey> primaryColums = new List<PrimaryKey>(); //保存主键列特性
foreach (PropertyInfo prop in propInfos)
{
if (prop.GetCustomAttributes(false).Length <= 0)
{
continue;
}
if (prop.GetCustomAttributes(false)[0] is PrimaryKey)
{
propPrimarys.Add(prop);
PrimaryKey primaryAttr = prop.GetCustomAttributes(typeof(PrimaryKey), false)[0] as PrimaryKey;
primaryColums.Add(primaryAttr);
}
}
这样我们就可以读取属性里所对应的数据库表里的主键了。
到这里我们基本已经掌握了利用反射读取和设置类属性值,设计自己的特性类,利用反射读取特性类的属性了。
下次我们就要开始持久层框架的设计了。
private static List<PropertyInfo> propPrimarys = new List<PropertyInfo>(); //保存主键列
private static List<PrimaryKey> primaryColums = new List<PrimaryKey>(); //保存主键列特性
foreach (PropertyInfo prop in propInfos)
{
if (prop.GetCustomAttributes(false).Length <= 0)
{
continue;
}
if (prop.GetCustomAttributes(false)[0] is PrimaryKey)
{
propPrimarys.Add(prop);
PrimaryKey primaryAttr = prop.GetCustomAttributes(typeof(PrimaryKey), false)[0] as PrimaryKey;
primaryColums.Add(primaryAttr);
}
}
这样我们就可以读取属性里所对应的数据库表里的主键了。
到这里我们基本已经掌握了利用反射读取和设置类属性值,设计自己的特性类,利用反射读取特性类的属性了。
下次我们就要开始持久层框架的设计了。
posted on 2007-11-05 19:33 wenwuxianren 阅读(6757) 评论(1) 编辑 收藏 举报