数据库三层一般的都是一层依赖一层的,这样依赖关系提高对后期开发扩展难免不变,而解决的方法也肯定不会只有一个的,在这里说的是利用反射来降低依赖性,提高扩展率。
namespace Student.DAL { public class Helper { public static List<T> GetPropertys<T>(SqlDataReader dr) { List<T> list = new List<T>(); Type t = typeof(T);//获取传过来的类型 PropertyInfo[] pis = t.GetProperties();//获取类型的所有公共属性 while (dr.Read()) { T obj = (T)Activator.CreateInstance(t);//创建指定的对象 foreach (PropertyInfo pi in pis) { pi.SetValue(obj, dr[pi.Name]); //给指定的对象赋值 } list.Add(obj);//把赋值好的对象添加到集合中 } return list; } public static T GetProperty<T>(SqlDataReader dr) { List<T> list = new List<T>(); Type t = typeof(T);//获取传过来的类型 PropertyInfo[] pis = t.GetProperties();//获取类型的所有公共属性 T obj = (T)Activator.CreateInstance(t);//创建指定的对象 foreach (PropertyInfo pi in pis) { pi.SetValue(obj, dr[pi.Name]); //给指定的对象赋值 } return obj; } public static SqlParameter[] GetParameters<T>(T t) { Type type = t.GetType(); List<SqlParameter> list = new List<SqlParameter>(); PropertyInfo[] ps = type.GetProperties();//获取指定类型的所有公共属性 foreach(PropertyInfo p in ps) { SqlParameter par = new SqlParameter("@"+p.Name,p.GetValue(t)); list.Add(par); } return list.ToArray();//把泛型转化为数组 } } }