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

本文介绍了一种使用C#实现的通用对象属性复制方法和列表类型转换的方法。通过反射获取源对象和目标对象的属性信息,将源对象的属性值赋给目标对象对应的属性,实现了对象的深拷贝。同时,提供了将一个类型的列表转换为另一个类型列表的功能。
 1         public static T2 CopyToModel<T1, T2>(T1 source)
 2         {
 3             T2 model = default(T2);
 4             PropertyInfo[] pi = typeof(T2).GetProperties();
 5             PropertyInfo[] pi1 = typeof(T1).GetProperties();
 6             model = Activator.CreateInstance<T2>();
 7             for (int i = 0; i < pi.Length; i++)
 8             {
 9                 pi[i].SetValue(model, pi1[i].GetValue(source, null), null);
10             }
11             return model;
12         }
13 
14         public static List<T2> CopyToList<T1, T2>(List<T1> source)
15         {
16             List<T2> t2List = new List<T2>();
17             T2 model = default(T2);
18             PropertyInfo[] pi = typeof(T2).GetProperties();
19             PropertyInfo[] pi1 = typeof(T1).GetProperties();
20             foreach (T1 t1Model in source)
21             {
22                 model = Activator.CreateInstance<T2>();
23                 for (int i = 0; i < pi.Length; i++)
24                 {
25                     pi[i].SetValue(model, pi1[i].GetValue(t1Model, null), null);
26                 }
27                 t2List.Add(model);
28             }
29             return t2List;
30         }

 

转载于:https://www.cnblogs.com/kliine/p/10978776.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值