Deep copy and shallow copy of C # deep learning----

Source: Internet
Author: User

I encountered a problem in programming, to assign a dependency property to a binding, to change a part of the attribute, all the values on the target of the binding have changed, which is not what I want, which leads to the problem of deep copy. (Please dabigatran exchange: 435226676)

First of all, when it comes to shades of paper, there's a natural problem. What is a deep copy and what is a shallow copy? The following is a detailed description of their definition.

  deep copy: refers to copying an object, not only the object's reference, but also the value referenced by the object is copied together. This makes the copy object of the deep copy independent of the source object, and any modification of the object will not affect the other object. For example, a person called Zhang San, and then use cloning technology to Sunline clone another person called John Doe, so Zhang San and John Doe is independent of each other, whether Zhang three missing arms or John Doe less legs will not affect another person. In the. NET realm, value objects are typical examples, such as int, double, struct and enum, and so on. The specific examples are as follows:

int Source = 123;//value type assignment internal execution deep copy int copy = source;//Assigning a Copy object does not change the value of the source object copy = 234;//also assigns a value to the source object does not change the value of the copied object source = 345;
Shallow copy: Refers to copying an object, copying only the reference of the object, but copying the object and the source object or referencing the same entity. At this point, the change of one of the objects affects the other object. For example, a person first called Zhang San, and later renamed the word Zhang Old three, but they are still the same person,
Whether Zhang is missing an arm or a old three less leg, all of them react to the same person. The reference type in. NET is an example. such as the class type. The specific examples are as follows:
public class person    {public        string Name {get; set;}    }    Class program    {        static void Main (string[] args)        {person            sourcep = new Person () {Name = "Zhang San"};            Person COPYP = SOURCEP; Shallow copy            copyp.name = "Zhang Old three";//Copy object change Name value            //result is "Zhang old three", because the implementation is a shallow copy, the change of one object will affect the other object            Console.WriteLine (" Person.name: [SOURCEP: {0}] [copyp:{1}] ", Sourcep.name, copyp.name);            Console.read ();        }    }
Comprehensive: deep copy and shallow copy mainly affect reference type, reference type shallow copy, copy is reference, deep copy, copy is entity, reference type shallow copy will change source

The implementation of a shallow copy:
System.Object.MemberwiseClone () method, which can be encapsulated if needed; reference type = also shallow copy
Deep Copy implementation: Reflection (Saving the original object to ensure that it does not reference each other), deserialization, visual tree
         Public StaticT deepcopywithreflection<t>(T obj) {type type=obj.            GetType (); //if the string or value type is returned directly            if(obj is string|| Type. Isvaluetype)returnobj; if(type. IsArray) {Type ElementType= Type.GetType (Type. Fullname.replace ("[]",string.                Empty)); varArray = obj asArray; Array copied=array.createinstance (ElementType, Array.                Length);  for(inti =0; I < array. Length; i++) {copied. SetValue (deepcopywithreflection (array.                GetValue (i)), i); }                return(T) convert.changetype (copied, obj.            GetType ()); }            Objectretval =activator.createinstance (obj.                        GetType ()); Propertyinfo[] Properties=obj. GetType (). GetProperties (BindingFlags.Public|BindingFlags.NonPublic| BindingFlags.Instance |bindingflags.static); foreach(varPropertyinchproperties) {                varPropertyValue = property. GetValue (obj,NULL); if(PropertyValue = =NULL)                    Continue; Property. SetValue (retval, Deepcopywithreflection (PropertyValue),NULL); }            return(T) retval; }
//using XML serialization and deserialization implementations         Public StaticT deepcopywithxmlserializer<t>(T obj) {Objectretval; using(MemoryStream ms =NewMemoryStream ()) {XmlSerializer XML=NewXmlSerializer (typeof(T)); Xml.                Serialize (MS, obj); Ms. Seek (0, Seekorigin.begin); retval=XML.                Deserialize (MS); Ms.            Close (); }            return(T) retval; }        //implementation using binary serialization and deserialization         Public StaticT deepcopywithbinaryserialize<t>(T obj) {Objectretval; using(MemoryStream ms =NewMemoryStream ()) {BinaryFormatter BF=NewBinaryFormatter (); //serializing into StreamsBF.                Serialize (MS, obj); Ms. Seek (0, Seekorigin.begin); //deserialization into an objectretval =BF.                Deserialize (MS); Ms.            Close (); }            return(T) retval; }        //using DataContractSerializer serialization and deserialization implementations         Public StaticT deepcopy<t>(T obj) {Objectretval; using(MemoryStream ms =NewMemoryStream ()) {DataContractSerializer Ser=NewDataContractSerializer (typeof(T)); Ser.                WriteObject (MS, obj); Ms. Seek (0, Seekorigin.begin); retval=ser.                ReadObject (MS); Ms.            Close (); }            return(T) retval; }

As for the visual tree, it is basically the new visil in WPF, etc.

Deep copy and shallow copy of C # deep learning----

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.