asp.net 使用反射给给实体赋值
实体类继承此基类
using System.Reflection; using System.Data.SqlClient; using System.Data; namespace Model { public class Base { protected bool isNull = true; public bool IsNull { get { return isNull; } set { isNull = value; } } protected void SetValue(object info) { foreach (FieldInfo fi in info.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance)) { fi.SetValue(this, fi.GetValue(info)); } } public void SetValue(SqlDataReader dr) { if (dr.Read()) { foreach (FieldInfo fi in this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance)) { if (fi.Name != "isNull") { fi.SetValue(this, dr[fi.Name]); } } this.isNull = false; } dr.Close(); } public void SetValue(DataTable dt) { if (dt != null && dt.Rows.Count > 0) { foreach (DataRow row in dt.Rows) { foreach (DataColumn column in dt.Columns) { FieldInfo fi = this.GetType().GetField(column.ColumnName); if (fi.Name != "isNull") { fi.SetValue(this, row[fi.Name]); } } } } } } }
实体类
namespace Model { public class Users: Base { protected String userid; public String UserId { get { return userid; } set { userid= value; } } protected String username; public String UserName { get { return username; } set { username= value; } } } }
给实体类赋值
public Users Get(String username) { Users info = new Users (); SqlParameter[] paras ={ new SqlParameter("@username",SqlDbType.NVarChar) }; paras[0].Value = username; SqlDataReader dr = DbHelper.ExecuteReader(CommandType.StoredProcedure, "GetUsersByUserName", paras); info.SetValue(dr); return info; }