.NET中制做对象的副本(二)继承对象之间的数据拷贝

定义学生

/// <summary>
    /// 学生信息
    /// </summary>
    public class Student
    {
        /// <summary>
        /// 学生姓名
        /// </summary>
        public string StudentName { get; set; }
    }

定义老师

    /// <summary>
    /// 老师信息
    /// </summary>
    public class Teacher
    {
        /// <summary>
        /// 老师姓名
        /// </summary>
        public string TeacherName { get; set; }
        /// <summary>
        /// 学生列表
        /// </summary>
        public List<Student> lists { get; set; }
    }

自定教授类

    public class Professor : Teacher
    {

    }

将t1对象拷贝到p1上

   Teacher t1 = new Teacher()
            {
                TeacherName = "老师1",
                lists = new List<Student> { new Student { StudentName = "学生1" }, new Student { StudentName = "学生2" } }
            };

            Professor p1 = new Professor()
            {
               
                lists = new List<Student> { },
            };
            CloneEntity(t1, p1);

 

实现代码如下

        //更新普通属性  
        private static void CloneProperty(PropertyInfo propertyInfo, object intrinsicObj, object newObj)
        {
            var data = propertyInfo.GetValue(newObj, null);
            if (data is IEnumerable<object>)
                CloneNavigationPropertyEntityCollection(propertyInfo, intrinsicObj, newObj);
            else
             propertyInfo.SetValue(intrinsicObj, data, null);
        }


        private static void CloneNavigationPropertyEntityCollection(PropertyInfo propertyInfo, object intrinsicObj, object newObj)
        {
            
            //获取上下文中匹配的原对象集合  
            var intrinsicData = propertyInfo.GetValue(intrinsicObj, null);
            //获取参数newObj中的对象集合  
            IEnumerable<object> newData = propertyInfo.GetValue(newObj, null) as IEnumerable<object>;
            var addMethod = intrinsicData.GetType().GetMethod("Add");
            foreach (object obj in newData)
            {

                Object objClone = GetIntrinsicObj(obj);
                objClone = CloneEntity(obj, objClone);
                addMethod.Invoke(intrinsicData, new object[] { objClone });
            }
        }

        //获取上下文中待更新的原对象  
        private static Object GetIntrinsicObj(Object entity)
        {
            Object intrinsicObj;
            intrinsicObj = Activator.CreateInstance(entity.GetType());

            return intrinsicObj;
        }

        //更新上下文中的原对象,返回值为更新后的原对象  
        public static Object CloneEntity(Object obj, Object intrinsicObj)
        {
            foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
            {
                CloneProperty(propertyInfo, intrinsicObj, obj);
            }
            return intrinsicObj;
        }

 下载源代码

posted on 2016-07-17 21:06  漫思  阅读(503)  评论(0编辑  收藏  举报

导航