shansun123 发表于 2013-2-5 01:27:17

使用反射机制遍历对象中的属性名及属性值

首先描述一种情景,当给你一个VO类(这个类是映射到数据库的表上的),现在让你把这个VO对象(已包含有效数据)另存为成XML文件,一般的做法可能是:
 
rows.SetAttribute("Adddate", ret.Adddate); 
 如果属性只有五六七八个还可以忍受手写的方式,如果多至十几乃至几十的情况下,手写已经超出了人的忍耐程度。下面给出一种解决方法,利用C#的反射机制自动生成这些XML节点(属性等)。
给出一个示例的VO类:
 
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace DataCenter.VO{    public class HousehireVO    {      private int _id;      private string _area;      private string _source;      private string _sphone;      private string _address;      private int _lc;      private string _hx;      private string _zhuangxiu;      private double _hireprice;      private int _bnuan;      private string _ptss;      private string _sysm;      private string _bphone;      private string _linkman;      private string _wtsm;      private DateTime _adddate;      private int _userid;      private int _deptid;      private string _deptName;      private int _invaliddate;      private string _gjxl;      private int _status;      private int _isAgreement;      private double _mj;      #region Constructors      public HousehireVO()      {      }      #endregion      #region Properties      //一些Setter/Getter      #endregion    }} 
上述这个类描述了一条房屋租赁信息。
 
不多废话,给出遍历属性的实现代码,如下:
 
List<VO.HousehireVO> ret ;                     //创建xml文档对象            XmlDocument doc = new XmlDocument();            //xml头            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", null)); //声明            //根元素            doc.AppendChild(doc.CreateElement("root")); //根节点            XmlElement[] rows = new XmlElement;            for (int i = 0; i < ret.Count; i++)            {                rows = doc.CreateElement("Info");                HousehireVO vo = ret;                Type vType = vo.GetType();                PropertyInfo[] vPropertyInfos = vType.GetProperties();                foreach (PropertyInfo vPropertyInfo in vPropertyInfos)                {                  rows.SetAttribute(vPropertyInfo.Name, vPropertyInfo.GetValue(ret, null);               }            } 
 
页: [1]
查看完整版本: 使用反射机制遍历对象中的属性名及属性值