Sample methods for cloning objects tutorial

Source: Internet
Author: User
Cloning objects are often encountered during the development process, sometimes need shallow cloning, sometimes need to deep cloning, the specific differences between them, and the implementation of the way there, summed up here.

There are several ways to implement deep cloning.

Manual

The code is as follows:

Manually copy var user2 = new User{id = user1. Id,name = new UserName {firstname= user1. Name.firstname,lastname= user1. Name.lastname}};

Reflection

The code is as follows:

1//Reflection 2 var User3 = user1. Copy () as User;

Extension methods:

 1 public static class Deepcopyhelper 2 {3 publicly static object Copy (This object obj) 4 {5 Object target Deepcopyobj; 6 Type targetType = obj. GetType ();         7//value type 8 if (Targettype.isvaluetype = = true) 9 {targetdeepcopyobj = obj;11 }12//reference type ELSE14 {targetdeepcopyobj = System.Activator.CreateInstance (targetty   PE); Create reference object system.reflection.memberinfo[] membercollection = obj. GetType ().                 GetMembers (); System.Reflection.MemberInfo member in membercollection) 19 {20 if (member. MemberType = = System.Reflection.MemberTypes.Field) {System.Reflection.FieldInfo F Ield = (System.Reflection.FieldInfo) member;23 Object fieldvalue = field. GetValue (obj); if (Fieldvalue is icloneable) . SetvAlue (Targetdeepcopyobj, (Fieldvalue as ICloneable). Clone ());}28 else29 {field. SetValue (Targetdeepcopyobj, Copy (Fieldvalue)),}32}34 else if (m Ember. MemberType = = System.Reflection.MemberTypes.Property) {System.Reflection.Property Info myproperty = (System.Reflection.PropertyInfo) member;37 MethodInfo info = Myproperty.getsetmethod ( FALSE) if (info! = null) The PropertyValue = M                             Yproperty.getvalue (obj, null); if (PropertyValue is icloneable) 42 {43 Myproperty.setvalue (Targetdeepcopyobj, (PropertyValue as ICloneable).                 Clone (), null),}45 else46 {47            Myproperty.setvalue (Targetdeepcopyobj, Copy (PropertyValue), null); 48}49 }50}52}53}54 return targetdeepcopyobj;55}56}
View Code

Serialization of

The code is as follows:

1//Serialization of 2 var user4 = user1. Deepclone ();

Extension methods:

1//<summary> 2//Deep clone 3///first serialization and re-serialization 4//</summary> 5//<typeparam name= "T" ></typeparam> 6//<param name= "obj" ></param> 7//<returns></returns> 8 public static T deepclone<t> (t His T obj) where T:class 9 {ten     return obj! = null? obj. ToJson (). Fromjson<t> (): null;11}
View Code

Other expressions are also used.

Summarize:

    1. Manual copy performance is best, but when you encounter very complex classes, the workload is great.

    2. Serialization is simpler than reflection and serialization.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.