c#通过反射获取类上的自定义特性
2009-12-01 18:29
639 查看
CPlayerInfo PlayerInfo = new CPlayerInfo ();
DataTable dt = new DataTable();
dt.Columns.Add("属性名称",typeof(string));
dt.Columns.Add("属性值", typeof(string));
DataRow dr = null;
System.Reflection.PropertyInfo[] ps = PlayerInfo.GetType().GetProperties();
foreach (System.Reflection.PropertyInfo pi in ps)
{
dr = dt.NewRow();
string name = pi.Name;
string value = Convert.ToString(pi.GetValue(PlayerInfo, null));
dr["属性名称"] = name;
dr["属性值"] = value;
dt.Rows.Add(dr);
}
gv_Roles.DataSource = dt;
gv_Roles.DataBind();
下面这个是笔者在以前的一个项目中用到的。当时是为了在导出excel报表的时侯,通过自定义特性,包含一些可配置的特性在里面。具体的操作excel不是本文重点,本文不会多做说明。下面只写个示例,简单说明一下如何通过反射获取自定义特性。示例只在类和属性上使用了自定义特性。读者可以按照实际的项目需求,合理使用自定义特性。
1、实现实体自定义特性,继承自Attribute类
![](http://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](http://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
Code
/// <summary>
/// 自定义特性 属性或者类可用 支持继承
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = true)]
public class EnitityMappingAttribute : Attribute
{
private string tableName;
/// <summary>
/// 实体实际对应的表名
/// </summary>
public string TableName
{
get { return tableName; }
set { tableName = value; }
}
private string columnName;
/// <summary>
/// 中文列名
/// </summary>
public string ColumnName
{
get { return columnName; }
set { columnName = value; }
}
}
注释中我已经写的很清楚,自定义特性中的属性一个是实体实际对应的数据库表名,一个是对应的中文列名称。
2、在实体中使用自定义特性
![](http://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](http://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
Code
/// <summary>
/// 会员 ,实际的表名叫MemberInfo,并不是和实体名一致
/// </summary>
[EnitityMapping(TableName="MemberInfo")]
public class Member
{
private int id;
[EnitityMapping(ColumnName="关键字")]
public int Id
{
get { return id; }
set { id = value; }
}
private string userName;
[EnitityMapping(ColumnName = "会员注册名")]
public string UserName
{
get { return userName; }
set { userName = value; }
}
private string realName;
[EnitityMapping(ColumnName = "会员真实名")]
public string RealName
{
get { return realName; }
set { realName = value; }
}
private bool isActive;
/// <summary>
/// 是否活跃 没有附加自定义属性
/// </summary>
public bool IsActive
{
get { return isActive; }
set { isActive = value; }
}
}
3、显示自定义特性
![](http://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](http://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
Code
class Program
{
/// <summary>
/// 通过反射取自定义属性
/// </summary>
/// <typeparam name="T"></typeparam>
private static void DisplaySelfAttribute<T>() where T:class ,new()
{
string tableName = string.Empty;
List<string> listColumnName = new List<string>();
Type objType = typeof(T);
//取属性上的自定义特性
foreach (PropertyInfo propInfo in objType.GetProperties())
{
object[] objAttrs = propInfo.GetCustomAttributes(typeof(EnitityMappingAttribute), true);
if (objAttrs.Length>0)
{
EnitityMappingAttribute attr = objAttrs[0] as EnitityMappingAttribute;
if (attr != null)
{
listColumnName.Add(attr.ColumnName); //列名
}
}
}
//取类上的自定义特性
object[] objs = objType.GetCustomAttributes(typeof(EnitityMappingAttribute), true);
foreach (object obj in objs)
{
EnitityMappingAttribute attr = obj as EnitityMappingAttribute;
if (attr != null)
{
tableName = attr.TableName;//表名只有获取一次
break;
}
}
if (string.IsNullOrEmpty(tableName))
{
tableName = objType.Name;
}
Console.WriteLine(string.Format("The tablename of the entity is:{0} ", tableName));
if (listColumnName.Count > 0)
{
Console.WriteLine("The columns of the table are as follows:");
foreach (string item in listColumnName)
{
Console.WriteLine(item);
}
}
}
static void Main(string[] args)
{
DisplaySelfAttribute<Member>(); //显示结果
Console.ReadLine();
}
}
ps:在获取自定义特性的地方,其实就是利用了GetCustomAttributes方法,这个没什么好说的。在实际开发的时候,通过反射的特性可以省却我们很多繁琐的事情,真像那句话说的,“反射反射,程序员的快乐”。不过,反射的性能问题还是需要格外注意的,比如,今天上午看到老赵的“Attribute操作的性能优化方式”才发现原来还有那么多内涵。
最后,再ps,某位jj在我的博客里寻人啊,见“这篇”和“这篇”的留言(注意日期,就是今天下午),关心一下。有认识的xdjm们通知一下这位大姐啊,谢谢热心的你鸟。
DataTable dt = new DataTable();
dt.Columns.Add("属性名称",typeof(string));
dt.Columns.Add("属性值", typeof(string));
DataRow dr = null;
System.Reflection.PropertyInfo[] ps = PlayerInfo.GetType().GetProperties();
foreach (System.Reflection.PropertyInfo pi in ps)
{
dr = dt.NewRow();
string name = pi.Name;
string value = Convert.ToString(pi.GetValue(PlayerInfo, null));
dr["属性名称"] = name;
dr["属性值"] = value;
dt.Rows.Add(dr);
}
gv_Roles.DataSource = dt;
gv_Roles.DataBind();
下面这个是笔者在以前的一个项目中用到的。当时是为了在导出excel报表的时侯,通过自定义特性,包含一些可配置的特性在里面。具体的操作excel不是本文重点,本文不会多做说明。下面只写个示例,简单说明一下如何通过反射获取自定义特性。示例只在类和属性上使用了自定义特性。读者可以按照实际的项目需求,合理使用自定义特性。
1、实现实体自定义特性,继承自Attribute类
![](http://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](http://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
Code
/// <summary>
/// 自定义特性 属性或者类可用 支持继承
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = true)]
public class EnitityMappingAttribute : Attribute
{
private string tableName;
/// <summary>
/// 实体实际对应的表名
/// </summary>
public string TableName
{
get { return tableName; }
set { tableName = value; }
}
private string columnName;
/// <summary>
/// 中文列名
/// </summary>
public string ColumnName
{
get { return columnName; }
set { columnName = value; }
}
}
注释中我已经写的很清楚,自定义特性中的属性一个是实体实际对应的数据库表名,一个是对应的中文列名称。
2、在实体中使用自定义特性
![](http://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](http://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
Code
/// <summary>
/// 会员 ,实际的表名叫MemberInfo,并不是和实体名一致
/// </summary>
[EnitityMapping(TableName="MemberInfo")]
public class Member
{
private int id;
[EnitityMapping(ColumnName="关键字")]
public int Id
{
get { return id; }
set { id = value; }
}
private string userName;
[EnitityMapping(ColumnName = "会员注册名")]
public string UserName
{
get { return userName; }
set { userName = value; }
}
private string realName;
[EnitityMapping(ColumnName = "会员真实名")]
public string RealName
{
get { return realName; }
set { realName = value; }
}
private bool isActive;
/// <summary>
/// 是否活跃 没有附加自定义属性
/// </summary>
public bool IsActive
{
get { return isActive; }
set { isActive = value; }
}
}
3、显示自定义特性
![](http://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](http://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
Code
class Program
{
/// <summary>
/// 通过反射取自定义属性
/// </summary>
/// <typeparam name="T"></typeparam>
private static void DisplaySelfAttribute<T>() where T:class ,new()
{
string tableName = string.Empty;
List<string> listColumnName = new List<string>();
Type objType = typeof(T);
//取属性上的自定义特性
foreach (PropertyInfo propInfo in objType.GetProperties())
{
object[] objAttrs = propInfo.GetCustomAttributes(typeof(EnitityMappingAttribute), true);
if (objAttrs.Length>0)
{
EnitityMappingAttribute attr = objAttrs[0] as EnitityMappingAttribute;
if (attr != null)
{
listColumnName.Add(attr.ColumnName); //列名
}
}
}
//取类上的自定义特性
object[] objs = objType.GetCustomAttributes(typeof(EnitityMappingAttribute), true);
foreach (object obj in objs)
{
EnitityMappingAttribute attr = obj as EnitityMappingAttribute;
if (attr != null)
{
tableName = attr.TableName;//表名只有获取一次
break;
}
}
if (string.IsNullOrEmpty(tableName))
{
tableName = objType.Name;
}
Console.WriteLine(string.Format("The tablename of the entity is:{0} ", tableName));
if (listColumnName.Count > 0)
{
Console.WriteLine("The columns of the table are as follows:");
foreach (string item in listColumnName)
{
Console.WriteLine(item);
}
}
}
static void Main(string[] args)
{
DisplaySelfAttribute<Member>(); //显示结果
Console.ReadLine();
}
}
ps:在获取自定义特性的地方,其实就是利用了GetCustomAttributes方法,这个没什么好说的。在实际开发的时候,通过反射的特性可以省却我们很多繁琐的事情,真像那句话说的,“反射反射,程序员的快乐”。不过,反射的性能问题还是需要格外注意的,比如,今天上午看到老赵的“Attribute操作的性能优化方式”才发现原来还有那么多内涵。
最后,再ps,某位jj在我的博客里寻人啊,见“这篇”和“这篇”的留言(注意日期,就是今天下午),关心一下。有认识的xdjm们通知一下这位大姐啊,谢谢热心的你鸟。
相关文章推荐
- c#通过反射获取类上的自定义特性
- c#通过反射获取类上的自定义特性
- c#通过反射获取类上的自定义特性
- c#通过反射获取类上的自定义特性
- c#通过反射获取类上的自定义特性
- C#中的特性 和 通过反射获取属性上的特性
- C# 反射通过GetCustomAttributes方法,获得自定义特性
- C# 反射通过GetCustomAttributes方法,获得自定义特性
- C# 通过反射获取MVC Controller里的类名,方法名,参数列表,返回值类型,Description描述,自定义Attribute
- c#通过反射获取自定义属性
- C# 反射通过GetCustomAttributes方法,获得自定义特性
- C#反射 获取程序集信息和通过类名创建类实例
- C#通过反射获取对象属性,打印所有字段属性的值
- .NET(C#):使用反射来获取枚举的名称、值和特性【转】
- C#通过反射获取按钮的文本
- Reflect 通过反射获取自定义注解值给另外一个对象赋值
- C#通过反射获取上层调用方法信息
- C#给枚举增加一个Attribute,并通过反射获取Attribute的值。(借鉴)
- C#反射 获取程序集信息和通过类名创建类实例
- 自己动手设计java web框架(二)-自定义注解以及通过反射获取注解