Table of Contents
Manual
Reflection
Serialization
Home Backend Development C#.Net Tutorial Example tutorial on how to clone an object

Example tutorial on how to clone an object

Jun 24, 2017 am 09:55 AM
clone several kinds object method

Cloning objects are often encountered during the development process. Sometimes shallow cloning is needed, and sometimes deep cloning is needed. What are the specific differences between them, and what are the implementation methods? Here is a summary.

There are several methods to implement deep cloning.

Manual

The code is as follows:

1

2

3

4

5

6

7

8

9

10

//手动复制

var user2 = new User

{

    Id = user1.Id,

    Name = new UserName

    {

        FirstName= user1.Name.FirstName,

        LastName= user1.Name.LastName

    }

};

Copy after login

Reflection

The code is as follows:

1

1 //反射2 var user3 = user1.Copy() as User;

Copy after login

Extension method:

1

1 public static class DeepCopyHelper 2 { 3     public static object Copy(this object obj) 4     { 5         Object targetDeepCopyObj; 6         Type targetType = obj.GetType(); 7         //值类型 8         if (targetType.IsValueType == true) 9         {10             targetDeepCopyObj = obj;11         }12         //引用类型 13         else14         {15             targetDeepCopyObj = System.Activator.CreateInstance(targetType);   //创建引用对象 16             System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();17 18             foreach (System.Reflection.MemberInfo member in memberCollection)19             {20                 if (member.MemberType == System.Reflection.MemberTypes.Field)21                 {22                     System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;23                     Object fieldValue = field.GetValue(obj);24                     if (fieldValue is ICloneable)25                     {26                         field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());27                     }28                     else29                     {30                         field.SetValue(targetDeepCopyObj, Copy(fieldValue));31                     }32 33                 }34                 else if (member.MemberType == System.Reflection.MemberTypes.Property)35                 {36                     System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;37                     MethodInfo info = myProperty.GetSetMethod(false);38                     if (info != null)39                     {40                         object propertyValue = myProperty.GetValue(obj, null);41                         if (propertyValue is ICloneable)42                         {43                             myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);44                         }45                         else46                         {47                             myProperty.SetValue(targetDeepCopyObj, Copy(propertyValue), null);48                         }49                     }50 51                 }52             }53         }54         return targetDeepCopyObj;55     }56 }

Copy after login
View Code

Serialization

The code is as follows:

1

1 //序列化2 var user4 = user1.DeepClone();

Copy after login

Extension method:

1

1 /// <summary> 2 /// 深克隆 3 /// 先序列化再反序列化 4 /// </summary> 5 /// <typeparam name="T"></typeparam> 6 /// <param name="obj"></param> 7 /// <returns></returns> 8 public static T DeepClone<T>(this T obj) where T : class 9 {10     return obj != null ? obj.ToJson().FromJson<T>() : null;11 }

Copy after login
View Code

Others also use expressions.

Summary:

  1. Manual copying has the best performance, but when encountering very complex classes, the workload is heavy.

  2. Compared with reflection and serialization, serialization is simpler.

The above is the detailed content of Example tutorial on how to clone an object. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. Mar 28, 2024 pm 12:50 PM

How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel.

How to enter bios on Colorful motherboard? Teach you two methods How to enter bios on Colorful motherboard? Teach you two methods Mar 13, 2024 pm 06:01 PM

How to enter bios on Colorful motherboard? Teach you two methods

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) May 01, 2024 pm 12:01 PM

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts)

Summary of methods to obtain administrator rights in Win11 Summary of methods to obtain administrator rights in Win11 Mar 09, 2024 am 08:45 AM

Summary of methods to obtain administrator rights in Win11

Quickly master: How to open two WeChat accounts on Huawei mobile phones revealed! Quickly master: How to open two WeChat accounts on Huawei mobile phones revealed! Mar 23, 2024 am 10:42 AM

Quickly master: How to open two WeChat accounts on Huawei mobile phones revealed!

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) May 04, 2024 pm 06:01 PM

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs)

Detailed explanation of Oracle version query method Detailed explanation of Oracle version query method Mar 07, 2024 pm 09:21 PM

Detailed explanation of Oracle version query method

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

How to set font size on mobile phone (easily adjust font size on mobile phone)

See all articles