• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

天心幽幽

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

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

定义特征类

实体类

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);

posted on 2011-07-08 10:28  天心幽幽  阅读(554)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3