C#对象深拷贝方法 - 通用版

来源:互联网 发布:注册域名能赚钱吗 编辑:程序博客网 时间:2024/06/04 03:48
  1. public object Copy(this object obj)  
  2.         {  
  3.             Object targetDeepCopyObj;  
  4.             Type targetType = obj.GetType();  
  5.             //值类型  
  6.             if (targetType.IsValueType == true)  
  7.             {  
  8.                 targetDeepCopyObj = obj;  
  9.             }  
  10.             //引用类型   
  11.             else  
  12.             {  
  13.                 targetDeepCopyObj = System.Activator.CreateInstance(targetType);   //创建引用对象   
  14.                 System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();  
  15.   
  16.                 foreach (System.Reflection.MemberInfo member in memberCollection)  
  17.                 {  
  18.                     if (member.MemberType == System.Reflection.MemberTypes.Field)  
  19.                     {  
  20.                         System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;  
  21.                         Object fieldValue = field.GetValue(obj);  
  22.                         if (fieldValue is ICloneable)  
  23.                         {  
  24.                             field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());  
  25.                         }  
  26.                         else  
  27.                         {  
  28.                             field.SetValue(targetDeepCopyObj, Copy(fieldValue));  
  29.                         }  
  30.   
  31.                     }  
  32.                     else if (member.MemberType == System.Reflection.MemberTypes.Property)  
  33.                     {  
  34.                         System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;  
  35.                         MethodInfo info = myProperty.GetSetMethod(false);  
  36.                         if (info != null)  
  37.                         {  
  38.                             object propertyValue = myProperty.GetValue(obj, null);  
  39.                             if (propertyValue is ICloneable)  
  40.                             {  
  41.                                 myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);  
  42.                             }  
  43.                             else  
  44.                             {  
  45.                                 myProperty.SetValue(targetDeepCopyObj, Copy(propertyValue), null);  
  46.                             }  
  47.                         }  
  48.   
  49.                     }  
  50.                 }  
  51.             }  
  52.             return targetDeepCopyObj;  
  53.         }  
0 0
原创粉丝点击