.net 反射实现两个相同结构实体类的转换

两个结构相同的实体类的转换,T2实体类的属性数可以大于T1的属性数,可用于api接口实体类参数到数据库实体的转换。

public static List<T2> CopyToList<T1, T2>(List<T1> source)

        {

            List<T2> t2List = new List<T2>();

            T2 model = default(T2);

            PropertyInfo[] pi = typeof(T2).GetProperties();

            PropertyInfo[] pi1 = typeof(T1).GetProperties();

            foreach (T1 t1Model in source)

            {

                model = Activator.CreateInstance<T2>();

                for(int i=0;i<pi.Length;i++)

                {

                    pi[i].SetValue(model, pi1[i].GetValue(t1Model, null), null);

                }

                t2List.Add(model);

            }

            return t2List;

        }


        public static T2 CopyToModel<T1, T2>(T1 source)

        {

            T2 model = default(T2);

            PropertyInfo[] pi = typeof(T2).GetProperties();

            PropertyInfo[] pi1 = typeof(T1).GetProperties();


            model = Activator.CreateInstance<T2>();

            for (int i = 0; i < pi.Length; i++)

            {

                pi[i].SetValue(model, pi1[i].GetValue(source, null), null);

            }


            return model;

        }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值