C USES reflection to implement deep copy methods for objects

  • 2020-05-12 02:59:56
  • OfStack

implementation

Copying child objects one by one is very labor-intensive, and if the child object is a reference type, you also need to consider whether to copy the child object one step deeper.

In practice, if a class has more than 10 child objects, copying them one by one is tedious and time-consuming for the developer.

So you use reflection to do that.

However, if the server is running, manual implementation is still recommended.

After all, reflection is a little bit slower than writing it out.

Code:


public static class DeepCopyHelper
  {
 
   public static object Copy(this object obj)
   {
     Object targetDeepCopyObj;
     Type targetType = obj.GetType();
     // Value types 
     if (targetType.IsValueType == true)
     {
       targetDeepCopyObj = obj;
     }
     // Reference types  
     else
     {
       targetDeepCopyObj = System.Activator.CreateInstance(targetType);  // Creating a reference object  
       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, Copy(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)
           {
             object propertyValue = myProperty.GetValue(obj, null);
             if (propertyValue is ICloneable)
             {
               myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);
             }
             else
             {
               myProperty.SetValue(targetDeepCopyObj, Copy(propertyValue), null);
             }
           }
 
         }
       }
     }
     return targetDeepCopyObj;
   }
 }

Related articles: