SoFunction
Updated on 2025-03-09

C# Use reflection to implement deep copying methods for objects

Implementation method

Copying sub-objects at one time by listing them one by one is very labor-intensive. If the sub-object is a reference type, you also need to consider whether to further copy the sub-objects.

In practical applications, if a class has dozens of sub-objects, copying one by one is boring and laborious for developers.

So it is done using reflection mechanism.
 
However, if it is running on the server side, it is recommended to implement it manually.

After all, the reflection mechanism is slower than writing it directly.

Code:

public static class DeepCopyHelper
  {
 
   public static object Copy(this object obj)
   {
     Object targetDeepCopyObj;
     Type targetType = ();
     //Value type     if ( == true)
     {
       targetDeepCopyObj = obj;
     }
     //Reference Type     else
     {
       targetDeepCopyObj = (targetType);  //Create a reference object       [] memberCollection = ().GetMembers();
 
       foreach ( member in memberCollection)
       {
         if ( == )
         {
            field = ()member;
           Object fieldValue = (obj);
           if (fieldValue is ICloneable)
           {
             (targetDeepCopyObj, (fieldValue as ICloneable).Clone());
           }
           else
           {
             (targetDeepCopyObj, Copy(fieldValue));
           }
 
         }
         else if ( == )
         {
            myProperty = ()member;
           MethodInfo info = (false);
           if (info != null)
           {
             object propertyValue = (obj, null);
             if (propertyValue is ICloneable)
             {
               (targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);
             }
             else
             {
               (targetDeepCopyObj, Copy(propertyValue), null);
             }
           }
 
         }
       }
     }
     return targetDeepCopyObj;
   }
 }

The above article C# uses reflection to achieve deep copying of objects is all the content I share with you. I hope you can give you a reference and I hope you can support me more.