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

来源:互联网 发布:淘宝商业模式分析 编辑:程序博客网 时间:2024/05/16 05:19

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

View Code

现在要将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中的属性值,依次赋给b44 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 }
复制代码
0 0