1       /// <summary>
 2         /// 根据反射给实体对象赋值
 3         /// </summary>
 4         /// <typeparam name="T">已赋值的对象</typeparam>
 5         /// <typeparam name="L">要被赋值的对象</typeparam>
 6         /// <param name="t">已赋值的对象的实例化</param>
 7         /// <returns></returns>
 8         public static L SetProperties<T, L>(T t) where L : new()
 9         {
10             if (t == null)
11             {
12                 return default(L);
13             }
14             System.Reflection.PropertyInfo[] propertiesT = typeof(T).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
15             System.Reflection.PropertyInfo[] propertiesL = typeof(L).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
16             //if (propertiesT.Length != propertiesL.Length || propertiesL.Length == 0)
17             //{
18             //    return default(L);
19             //}
20             L setT = new L();
21             foreach (System.Reflection.PropertyInfo itemL in propertiesL)
22             {
23                 foreach (System.Reflection.PropertyInfo itemT in propertiesT)
24                 {
25 
26                     if (itemL.Name == itemT.Name)
27                     {
28 
29                         object value = itemT.GetValue(t, null);
30 
31                         itemL.SetValue(setT, value == null ? null : Convert.ChangeType(value, itemL.PropertyType), null);
32                     }
33                 }
34             }
35             return setT;
36         }
posted on 2015-11-18 17:10  Wendell-Wang  阅读(323)  评论(0编辑  收藏  举报