利用反射实现两个对象赋值
发布时间:2020-12-17 00:56:54 所属栏目:安全 来源:网络整理
导读:利用反射实现对象转字符串 private string SpellEntityT(T entity) { string result = ""; Type Keytype = typeof(T); PropertyInfo[] piKey = Keytype.GetProperties();//获取属性集合 foreach (PropertyInfo p in piKey) { result += p.Name + ":" + p.Get
利用反射实现对象转字符串 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(','); }
?学生实体类: 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(); 此方法可以写成一个通用类,利用泛型操作实现不同实体转换。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |