利用反射实现两个对象赋值
2012-06-20 11:37
176 查看
利用反射实现对象转字符串
private string SpellEntity<T>(T entity) { string result = ""; Type Keytype = typeof(T); PropertyInfo[] piKey = Keytype.GetProperties();//获取属性集合 foreach (PropertyInfo p in piKey) { result += p.Name + ":" + p.GetValue(entity, null) + ","; } return result.Trim(','); }
在通过webservice或者wcf应用中经常会用到实体间转换的问题,当字段很多时进行赋值很麻烦,通过反射可以实现快速自动化赋值:
学生实体类:
public class Student { public string Name { set; get; } public string Sex { set; get; } public int Age { set; get; } }
老师实体类:
public class Teacher { public string Name { set; get; } public string Sex { set; get; } public int Age { set; get; } }
简单实现:
Student student = new Student(); student.Name = "EP"; student.Sex = "Male"; student.Age = 30; Teacher teacher = new Teacher(); Type t = typeof(Student); PropertyInfo[] pi = t.GetProperties(); Console.WriteLine(typeof(Student)); foreach (PropertyInfo p in pi) { Console.WriteLine(p.Name + "--" + p.PropertyType + "--" + p.GetValue(student, null)); PropertyInfo pii = (typeof(Teacher)).GetProperty(p.Name); pii.SetValue(teacher, p.GetValue(student,null), null); } Console.ReadLine(); t = typeof(Teacher); pi = t.GetProperties(); Console.WriteLine(typeof(Teacher)); foreach (PropertyInfo p in pi) { Console.WriteLine(p.Name + "--" + p.PropertyType + "--" + p.GetValue(teacher, null)); } Console.ReadLine();
此方法可以写成一个通用类,利用泛型操作实现不同实体转换。
相关文章推荐
- 利用java反射实现两个具有相同属性bean赋值
- C#利用反射实现两个类的对象之间相同属性的值的复制
- 转 利用java反射实现两个具有相同属性bean赋值
- C#利用反射实现两个类的对象之间相同属性的值的复制
- 利用java反射实现两个具有相同属性bean赋值
- Java利用反射实现对象转json
- 自己在项目中的学习总结:利用工厂模式+反射机制+缓存机制,实现动态创建不同的数据层对象接口
- Java利用反射实现对象之间相同属性复制
- 利用反射实现对象调用方法
- 利用反射实现实体类自动赋值
- C#用反射实现两个类的对象之间相同属性的值的复制
- c#利用反射,实现将model类变成字符串、再还原成mode对象的功能
- 同类型对象利用反射自动赋值
- 利用Java反射实现JavaBean对象相同属性复制并初始化目标对象为空的属性的BeanUtils
- c# 利用反射动态给实体类对象赋值
- 利用反射给对象中的某个属性赋值或取值
- Linq 实现两个对象实例List之间的赋值
- [.net 面向对象程序设计进阶] (20) 反射(Reflection)(上)利用反射技术实现动态编程
- 利用反射实现mysql数据库sql查询 返回List<E>泛型(持久化)对象
- Java -- 利用反射实现对象之间相同属性复制BeanUtil