通过反射获取对象属性及特征

定义特征类

实体类

using System;
using System.Collections.Generic;
using System.Text;

namespace WindowsFormsApplication1
{
/// <summary>
/// 类名:Model_T_BAS_AUTHORITY
/// 命名空间:Model
/// 类功能描述:实体类
/// </summary>
/// 创建者:黄四虎
/// 创建时间:2011-5-26 15:06:25
/// 修改标识:
/// ----------------------------------------------------------------------------------------
[Serializable]
[EnitityMapping(TableName
= "权限")]
public class Model_T_BAS_AUTHORITY
{
/// <summary>
/// 权限ID
/// </summary>
[EnitityMapping(ColumnName = "权限ID",DataType = "System.String")]
public string bas_authority_code {get;set;}
/// <summary>
/// 权限名称
/// </summary>
[EnitityMapping(ColumnName = "权限名称",DataType = "System.String")]
public string bas_authority_name {get;set;}
/// <summary>
/// 排序号
/// </summary>
[EnitityMapping(ColumnName = "排序号", DataType = "System.Decimal")]
public Decimal? sort_order {get;set;}


}
}

反射

public void fsmodel(object o)
{
string table = string.Empty;
Type t
= o.GetType();
table
= t.Name;
object[] objs = t.GetCustomAttributes(typeof(EnitityMappingAttribute), true);
foreach (object obj in objs)
{
EnitityMappingAttribute attr
= obj as EnitityMappingAttribute;
if (attr != null)
{
table
= table + " " +attr.TableName;//表名只有获取一次
break;
}
}
System.Reflection.PropertyInfo[] ps
= t.GetProperties();
foreach (System.Reflection.PropertyInfo pi in ps)
{

string aa = string.Empty;
object[] objAttrs = pi.GetCustomAttributes(typeof(EnitityMappingAttribute), true);
if (objAttrs.Length > 0)
{
EnitityMappingAttribute attr
= objAttrs[0] as EnitityMappingAttribute;
if (attr != null)
{
aa
=" " + attr.ColumnName + " " + attr.DataType; //列名
}
}
aa
=aa + " " + pi.Name + " " + pi.GetValue(o, null) + "\n";
this.textBox1.AppendText(table + aa );
}



}

调用

Model_T_BAS_AUTHORITY m = new Model_T_BAS_AUTHORITY();
m.bas_authority_code
= "112233";
m.bas_authority_name
= "334455";
m.sort_order
= 1;

fsmodel(m);
原文地址:https://www.cnblogs.com/txsoft/p/2100736.html