.net two identical structure to achieve the conversion by the reflection entity classes

 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         }
 1         public static List<T2> CopyToList<T1, T2>(List<T1> source)
 2         {
 3             List<T2> t2List = new List<T2>();
 4             T2 model = default(T2);
 5             PropertyInfo[] pi = typeof(T2).GetProperties();
 6             PropertyInfo[] pi1 = typeof(T1).GetProperties();
 7             foreach (T1 t1Model in source)
 8             {
 9                 model = Activator.CreateInstance<T2>();
10                 for (int i = 0; i < pi.Length; i++)
11                 {
12                     pi[i].SetValue(model, pi1[i].GetValue(t1Model, null), null);
13                 }
14                 t2List.Add(model);
15             }
16             return t2List;
17         }

 

Guess you like

Origin www.cnblogs.com/kliine/p/10978776.html