C#深拷贝 反射实现

来源:互联网 发布:北京青旅推荐 知乎女性 编辑:程序博客网 时间:2024/04/29 14:26
项目中经常遇到需要将一个对象深拷贝出来做其他事情,而原对象保持原有状态的情况。
当时又不想自己new一个出来,然后对着一堆字段赋值......

多次遇到这样的需求后就想着用反射实现。


#region 对象拷贝//引入命名空间using System.Reflection;         /// <summary>        /// 对象拷贝        /// </summary>        /// <param name="obj">被复制对象</param>        /// <returns>新对象</returns>        private static object CopyOjbect(object obj)        {            if (obj == null)            {                return null;            }            //拷贝目标            Object targetDeepCopyObj;            //元类型            Type targetType = obj.GetType();            //值类型              if (targetType.IsValueType == true)            {                targetDeepCopyObj = obj;            }            //引用类型               else            {                //创建引用对象                targetDeepCopyObj = System.Activator.CreateInstance(targetType);                  //获取引用对象的所有公共成员                System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();                foreach (System.Reflection.MemberInfo member in memberCollection)                {                    //拷贝字段                    if (member.MemberType == System.Reflection.MemberTypes.Field)                    {                        System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;                        Object fieldValue = field.GetValue(obj);                        if (fieldValue is ICloneable)                        {                            field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());                        }                        else                        {                            field.SetValue(targetDeepCopyObj, CopyOjbect(fieldValue));                        }                    }//拷贝属性                    else if (member.MemberType == System.Reflection.MemberTypes.Property)                    {                        System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;                        MethodInfo info = myProperty.GetSetMethod(false);                        if (info != null)                        {                            try                            {                                object propertyValue = myProperty.GetValue(obj, null);                                if (propertyValue is ICloneable)                                {                                    myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);                                }                                else                                {                                    myProperty.SetValue(targetDeepCopyObj, CopyOjbect(propertyValue), null);                                }                            }                            catch (System.Exception ex)                            {                                //TODO                                //输出你要处理的异常代码                            }                        }                    }                }            }            return targetDeepCopyObj;        }         #endregion

测试

public class City      {        public string code { get; set; }        public string name { get; set; }        public string provincecode { get; set; }    }    City city1 = new City();            city1.code = "1111";            city1.name = "2222";            city1.provincecode = "33333";            City city2 = (City)CopyOjbect(city1);            city2.name = "修改NAME";            Console.WriteLine(city1.name);            Console.WriteLine(city2.name);   //输出  2222   修改NAME


1 0
原创粉丝点击