【C#】Deep copy of objects

If you learned C++ carefully, you must have known something about the copy of object.

For example, I defined a class called (ABC),and two variable (x) and (y) are (ABC)s.

Like this:

 1 class ABC{
 2     public:
 3         int a,b;
 4 };
 5 int main(){
 6     ABC x,y;
 7     x.a=1;x.b=2;
 8     y=x;
 9     y.a=3;
10     return 0;    
11 };

Certainly,( y.a==3 , y.b==2 ), and, what's more,  ( x.a==1,x.b==2 ).

So in fact,a deep copy was made in the line 8.

But in C#,this can be different, if you operate like this, ( x.a==3,x.b==2 ) would be the result, for x and y is the same variable.

So how can we make a deep copy? Do not worry,we can serialize it and then turn it back!

(Remember : Don't forget to put a ([Serializable]) before the defination of the object!!!)

Enjoy it:(Line 31-35)

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.IO;
 7 using System.Runtime;
 8 using System.Runtime.Serialization.Formatters.Binary;
 9 using System.Runtime.Serialization;
10 using System.Runtime.InteropServices;
11 
12 namespace DataTrans
13 {
14     public class Switcher  
15     {
16         public byte[] Object2Bytes(object obj)
17         {
18             IFormatter fmt = new BinaryFormatter();
19             MemoryStream ms = new MemoryStream();
20             fmt.Serialize(ms, obj);
21             return ms.GetBuffer();
22         }
23 
24         public object Bytes2Object(byte[] bt)
25         {
26             IFormatter fmt = new BinaryFormatter();
27             MemoryStream ms = new MemoryStream(bt);
28             return (object)fmt.Deserialize(ms);
29         }
30 
31         public T DeepCopy<T>(T __dt)  
32         {
33             byte[] bt = Object2Bytes(__dt);  //serialize
34             return (T)Bytes2Object(bt);  //deserialize
35         }
36 
37         public Switcher()
38         {
39         }
40     }
41 }
原文地址:https://www.cnblogs.com/Fefnir/p/5912815.html