C # copy

Source: Internet
Author: User

In c #, the type is divided into the value type and the reference type. The value-type object Value assignment is itself a copy of the given itself. When the reference type value is assigned, it is assigned a value pointing to the memory on the stack, what should we do if we don't want to assign this address and want to assign the object to it? First, you need to know that the copy can be divided into the superficial copy and the deep copy. The superficial copy gets a new instance, and a copy of the original object type and value type field is the same. However, if the field is of the reference type, it copies the reference instead of the object. If you want to copy the object of the referenced field, it is called Deep copy. This article summarizes the following methods for copying. 1. the first is the most stupid method. The legendary "manual copy" is to assign all value objects in the reference and string objects with value characteristics to the new objects one by one, in this way, the Code volume is too large and maintenance is quite troublesome, so you don't need it if you don't need it. 2. System. Object provides the protected method MemberwiseClone, which can be used for "superficial" copying. Because this method is marked as "protected", we can only access this method within the inheritance class or class. Copy the public class A {public string rr {get; set;} public string tt {get; set;} public A ShallowCopy () {return (A) this. memberwiseClone () ;}} copy code 3. serialization and deserialization are used. Although deep copying can be achieved, this method is a bit tricky to crack mosquitoes, remember to close the created MemoryStream stream copy code public static object Clone (object o, out MemoryStream MS) {BinaryFormatter bf = new BinaryFormatter (); MS = new MemoryStream (); bf. serialize (ms, o); ms. seek (0, SeekOrigin. B Egin); return bf. Deserialize (MS);} copies Code 4. In a blog written by a foreigner (http://www.codeproject.com/Articles/3441/Base-class-for-cloning-an-object-in-C), this problem was solved using a reflection method. He wrote a BaseObject class. If we inherit this class, we can implement deep copy. The following is his Implementation Method: Create an abstract class with default behaviors to implement the ICloneable interface, the default behavior is to use the following library functions to copy every field in the class. 1. Traverse each field in the class to see if the ICloneable interface is supported. 2. If the ICloneable interface is not supported, set it according to the following rules. That is to say, if the field is of a value type, copy it. If it is of a reference type, the copy field points to an object. 3. If ICloneable is supported, use its clone method in the Cologne object to set it. 4. If the field supports the IEnumerable interface, check whether it supports the IList or idireary ary interface. If yes, check whether the ICloneable interface is supported by the iteration set. All we need to do is make all fields support the ICloneable interface. The following is the test result: copy the code public class MyClass: BaseObject {public string myStr = "test"; public int id;} public class MyContainer: BaseObject {public string name = "test2 "; public MyClass [] myArray = new MyClass [5]; public class MyContainer () {for (int I = 0; I <5; I ++) {this. myArray [I] = new MyClass () ;}} copy code static void Main (string [] args) {MyContainer con1 = new MyContainer (); MyContainer con2 = (MyCo Ntainer) con1.Clone (); con2.myArray [0]. id = 5;} in the copy code con2, the first element in the MyClass instance is changed to 5, but con1 is not changed, that is, deep copy is implemented. BaseObject implementation: copy the code /// <summary> // BaseObject class is an abstract class for you to derive from. /// Every class that will be dirived from this class will support the // Clone method automaticly. <br> // The class implements the interface ICloneable and there // for every object that will be derived <br> // from this object will support the ICloneable interface as well. /// </summary> public abstr Act class BaseObject: ICloneable {// <summary> // Clone the object, and returning a reference to a cloned object. /// </summary> /// <returns> Reference to the new cloned // object. </returns> public object Clone () {// First we create an instance of this specific type. object newObject = Activator. createInstance (this. getType (); // We get the array of fields for the new type instance. fieldInfo [] Fields = newObject. getType (). getFields (); int I = 0; foreach (FieldInfo fi in this. getType (). getFields () {// We query if the fiels support the ICloneable interface. type ICloneType = fi. fieldType. getInterface ("ICloneable", true); if (ICloneType! = Null) {// Getting the ICloneable interface from the object. ICloneable IClone = (ICloneable) fi. getValue (this); // We use the clone method to set the new value to the field. fields [I]. setValue (newObject, IClone. clone ();} else {// If the field doesn't support the ICloneable // interface then just set it. fields [I]. setValue (newObject, fi. getValue (this);} // Now we check if the object suppo Rt the // IEnumerable interface, so if it does // we need to enumerate all its items and check if // they support the ICloneable interface. type IEnumerableType = fi. fieldType. getInterface ("IEnumerable", true); if (IEnumerableType! = Null) {// Get the IEnumerable interface from the field. IEnumerable IEnum = (IEnumerable) fi. getValue (this); // This version supports the IList and the // IDictionary interfaces to iterate on collections. type IListType = fields [I]. fieldType. getInterface ("IList", true); Type IDicType = fields [I]. fieldType. getInterface ("IDictionary", true); int j = 0; if (IListType! = Null) {// Getting the IList interface. IList list = (IList) fields [I]. getValue (newObject); foreach (object obj in IEnum) {// Checking to see if the current item // support the ICloneable interface. ICloneType = obj. getType (). getInterface ("ICloneable", true); if (ICloneType! = Null) {// If it does support the ICloneable interface, // we use it to set the clone of // the object in the list. ICloneable clone = (ICloneable) obj; list [j] = clone. clone ();} // NOTE: if the item in the list is not // support the ICloneable interface then in the // cloned list this item will be the same // item as in the original list // (as long as this type is a reference type ). j ++ ;}} else if (IDicType! = Null) {// Getting the dictionary interface. IDictionary dic = (IDictionary) fields [I]. getValue (newObject); j = 0; foreach (DictionaryEntry de in IEnum) {// Checking to see if the item // support the ICloneable interface. ICloneType = de. value. getType (). getInterface ("ICloneable", true); if (ICloneType! = Null) {ICloneable clone = (ICloneable) de. value; dic [de. key] = clone. clone ();} j ++ ;}}} I ++ ;}return newObject ;}people who copy code are easy to ask: What should I learn? ---- don't ask, that's right. impetuous people may easily ask: do JS have money? ---- we suggest you grab a bank. impetuous people may say: I want a Chinese version! I cannot use English! ---- No? Learn! Impetuous people can be divided into two types: those who only wait and do not learn; those who only learn but do not insist; impetuous people will never be a master.

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.