【C#】Deep copy of objects

时间:2023-03-08 16:53:34
【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:

 class ABC{
public:
int a,b;
};
int main(){
ABC x,y;
x.a=;x.b=;
y=x;
y.a=;
return ;
};

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)

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Runtime.InteropServices; namespace DataTrans
{
public class Switcher
{
public byte[] Object2Bytes(object obj)
{
IFormatter fmt = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
fmt.Serialize(ms, obj);
return ms.GetBuffer();
} public object Bytes2Object(byte[] bt)
{
IFormatter fmt = new BinaryFormatter();
MemoryStream ms = new MemoryStream(bt);
return (object)fmt.Deserialize(ms);
} public T DeepCopy<T>(T __dt)
{
byte[] bt = Object2Bytes(__dt); //serialize
return (T)Bytes2Object(bt); //deserialize
} public Switcher()
{
}
}
}