C#通过反射实现两个对象相同属性值的复制
类A
1 /// <summary> 2 /// 类A 3 /// </summary> 4 public class TypeA 5 { 6 public int ID { get; set; } 7 public string Name { get; set; } 8 }
类B
1 /// <summary> 2 /// 类B 3 /// </summary> 4 public class TypeB 5 { 6 public int ID { get; set; } 7 public string Name { get; set; } 8 public string Age { get; set; } 9 }
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 { 20 /// <summary> 21 /// 将Tsource类中的属性拷贝到T中 22 /// </summary> 23 /// <typeparam name="T">拷贝目标实体类</typeparam> 24 /// <typeparam name="Tsource">源实体类</typeparam> 25 /// <param name="source"></param> 26 /// <returns></returns> 27 public static T ShallowCopy<T, Tsource>(Tsource source) 28 { 29 T t = Activator.CreateInstance<T>(); 30 try 31 { 32 var sourceType = source.GetType();//获得类型 33 var Typed = typeof(T); 34 foreach (PropertyInfo sp in Typed.GetProperties())//获得类型的属性字段 35 { 36 var sValue = sourceType.GetProperty(sp.Name); // 找到源实体类的属性信息 37 if (sValue != null) 38 { 39 sp.SetValue(t, sValue.GetValue(source, null), null); 40 } 41 } 42 } 43 catch (Exception ex) 44 { 45 throw ex; 46 } 47 return t; 48 } 49 50 /// <summary> 51 /// 将Tsource类中的属性用深拷贝到T中 52 /// </summary> 53 /// <typeparam name="T">拷贝目标实体类</typeparam> 54 /// <typeparam name="Tsource">源实体类</typeparam> 55 /// <param name="source"></param> 56 /// <returns></returns> 57 public static T DeepCopy<T, Tsource>(Tsource source) 58 { 59 //TODO 采用序列化的方式进行深拷贝 60 61 return default(T); 62 } 63 64 } 65 }
将类TypeB与类TypeA相同的属性进行复制,可以用下面的ShallCopy方法进行实现,调用方式如下
1 TypeB b = new TypeB(); 2 b.ID = 1; 3 b.Name = "这是A"; 4 b.Age = 18; 5 TypeA a = ShallCopy<TypeA, TypeB>(b);