反射 实体类的赋值/取值问题

前段时间遇到个很郁闷的情况,2个实体类里面的属性字段都差不多。唯一不同的就是一个类比另一个类多几个字段

View Code
 1 public class A
 2 {
 3         public int ID
 4         {
 5             get;
 6             set;
 7         }
 8         public string name
 9         {
10             get;
11             set;
12         }
13         public DateTime addDate
14        {
15              get;
16               set;
17          }
18 }
19 
20 public class B
21 {
22         public int ID
23         {
24             get;
25             set;
26         }
27        public string name
28         {
29             get;
30             set;
31         }
32        public DateTime addDate
33       {
34           get;
35           set;
36        }
37        public int classID
38        {
39            get;
40            set;
41        } 
42        public int className
43        {
44            get;
45            set;
46         } 
47 }

现在要将A类的值赋给B类

如果说一个字段一个字段赋值,那样子觉得写得太死了。但是一下子还没想出什么好方法,只有用反射了。。

 1        
 2         /// <summary>
 3         /// 实体类赋值
 4         /// </summary>
 5         /// <param name="filename">属性名</param>
 6         /// <param name="comment">源实体类</param>
 7         /// <param name="commenturl">目的实体类</param>
 8         /// <returns></returns>
 9         private CommentUrl switchType(string filename, A a, B b)
10         {
11             
12             Type aType = A.GetType();
13             Type bType = B.GetType();
14             string type = bType.GetProperty(filename).PropertyType.Name;//得到数据类型
15             
//如果a中该字段为空,则返回 16 if (bType.GetProperty(filename).GetValue(a, null) == null) 17 return b; 18 19 switch (type) 20 { 21 case "Int32": 22 int nValue = Convert.ToInt16(aType.GetProperty(filename).GetValue(a, null));//获取a对象中的值 23 b.GetProperty(filename).SetValue(b, nValue, null);//赋值给b对象 24 break; 25 26 case "String": 27 string sValue = aType.GetProperty(filename).GetValue(a, null).ToString(); 28 b.GetProperty(filename).SetValue(b, sValue, null); 29 break; 30 case "DateTime": 31 DateTime dValue = Convert.ToDateTime(aType.GetProperty(filename).GetValue(a, null)); 32 b.GetProperty(filename).SetValue(b, dValue, null); 33 break; 34 case "Boolean": 35 bool bValue = Convert.ToBoolean(aType.GetProperty(filename).GetValue(a, null)); 36 b.GetProperty(filename).SetValue(b, bValue, null); 37 break; 38 } 39 40 return b; 41 } 42 43 //调用此类,已存在 a 对象,将a中的属性值,依次赋给b 44 B b = new B(); 45 PropertyInfo[] info = typeof(A).GetProperties(); 46 //循环属性 47 foreach (PropertyInfo fileinfo in info) 48 { 49 b = switchType(fileinfo.Name, a, b); 50 }
posted @ 2012-05-18 10:44  Tsong Chen  阅读(2043)  评论(2编辑  收藏  举报