C#通过反射实现两个对象相同属性值的复制

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Security.Permissions;
 5 using System.Data;
 6 using MySql.Data;
 7 using System.Configuration;
 8 using System.IO;
 9 using System.Text;
10 using System.Reflection; 
11 using MySql.Data.MySqlClient;
12 using System.Runtime.Serialization;
13 using System.Runtime.Serialization.Formatters.Binary;
14 
15 
16 namespace WebApplication1.Common
17 {
18     public static class ConvertUtil
19     {
21         /// <summary>
22         ///23         /// 将Tsource类中的属性拷贝到T中
24         /// </summary>
25         /// <typeparam name="T">拷贝目标实体类</typeparam>
26         /// <typeparam name="Tsource">源实体类</typeparam>
27         /// <param name="source"></param>
28         /// <returns></returns>
29         public static T ShallowCopy<T, Tsource>(Tsource source)
30         {
31             T t = Activator.CreateInstance<T>();
32             try
33             {
34                 var sourceType = source.GetType();//获得类型
35                 var Typed = typeof(T);
36                 foreach (PropertyInfo sp in Typed.GetProperties())//获得类型的属性字段
37                 {
38                     var sValue = sourceType.GetProperty(sp.Name); // 找到源实体类的属性信息
44                     if (sValue != null)
45                     {
46                         sp.SetValue(t, sValue.GetValue(source, null), null);
47                     }
48                 }
49             }
50             catch (Exception ex)
51             {
52                 throw ex;
53             }
54             return t;
55         }
56 
57         /// <summary>
58         ///59         /// 将Tsource类中的属性用深拷贝到T中
60         /// </summary>
61         /// <typeparam name="T">拷贝目标实体类</typeparam>
62         /// <typeparam name="Tsource">源实体类</typeparam>
63         /// <param name="source"></param>
64         /// <returns></returns>
65         public static T DeepCopy<T, Tsource>(Tsource source)
66         {
67             //TODO  采用序列化的方式进行深拷贝
68 
82             return default(T);
83         }
84 
85     }
86 }

猜你喜欢

转载自www.cnblogs.com/MacrossFT/p/9652706.html