通过反射的方法,将源对象属性的值赋给目标对象的相同属性
一个将源对象属性的值赋给目标对象的通用方法,提高书写代码的效率。
1 public class CommonMethods
2 {
3 /// <summary>
4 /// 通过反射的方法,将源对象属性的值赋给目标对象的相同属性
5 /// </summary>
6 /// <param name="source">源对象</param>
7 /// <param name="dest">目标对象</param>
8 public static void GetSomePropertyValues(object source, object dest)
9 {
10 Type sourceType = source.GetType();
11 Type destType = dest.GetType();
12 foreach (var s in sourceType .GetProperties ())
13 {
14 foreach (var d in destType .GetProperties())
15 {
16 if ((d.Name == s.Name) && (d.PropertyType == s.PropertyType))
17 {
18 d.SetValue(dest, s.GetValue(source, null), null);
19 }
20 }
21 }
22 }
23 }
希望对新手有用。
浙公网安备 33010602011771号