反射辅助类

数据库三层一般的都是一层依赖一层的,这样依赖关系提高对后期开发扩展难免不变,而解决的方法也肯定不会只有一个的,在这里说的是利用反射来降低依赖性,提高扩展率。

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();//把泛型转化为数组
        }
    }
}
View Code

 

转载于:https://www.cnblogs.com/LiuZhen/p/3585838.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值