. NET-based deep replication and shortest replication,. net-based depth
I have never figured out the difference between deep replication and simple replication. Today I fully understand this and write it out to encourage me.
If you do not know the difference between the value type and the reference type, refer to the values first.
As we all know, an Object is a common base class of all classes. Its method is MemberwiseClone () and its purpose is
Public class Content {public int Val;} public class Cloner {public Content MyContent = new Content (); public Cloner (int newVal) {MyContent. val = newVal;} public object GetCopy () {return MemberwiseClone ();}}
Here we have two classes. One Content class has only one Val of the Value Type int, And the other class is a Cloner class with a member of the Content type, then there is a constructor that can initialize members. Finally, there is a GetCopy method, which is used to copy itself through the MemberwiseClone method.
The following code calls the Cloner class:
Static void Main (string [] args) {Cloner source = new Cloner (10); Cloner target = (Cloner) source. getCopy (); // The returned Object type requires type conversion. console. writeLine ("target. myContent. val = {0} ", target. myContent. val); source. myContent. val = 15; Console. writeLine ("target. myContent. val = {0} ", target. myContent. val); Console. readKey ();}
The result is:
// Abstract: // supports cloning. You can create a new instance with the same value as an existing instance. [ComVisible (true)] public interface ICloneable {// Abstract: // create a new object as a copy of the current instance. //// Return result: // as a new object of this instance copy. Object Clone ();}
In the above example, we only need to modify some code:
public class Cloner:ICloneable { public Content MyContent = new Content(); public Cloner(int newVal) { MyContent.Val = newVal; } //public object GetCopy() //{ // return MemberwiseClone(); //} public object Clone() { Cloner cloned = new Cloner(MyContent.Val); return cloned; } }
In order to make a difference, I put the previous code above. The annotated code is a simple copy, followed by a deep copy. We can see that the difference is that the MyContent of this instance is used. val re-generates the instance and returns it to the target. The test result is:
Public object Clone () {Cloner cloned = new Cloner (); cloned. MyContent = MyContent. Clone (); return cloned ;}
In this way, the key is to create a new object instance and return it instead of returning the original object instance. Do you understand?