微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

利用反射实现两个对象赋值

利用反射实现对象转字符串
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();

方法可以写成一个通用类,利用泛型操作实现不同实体转换。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐