【C#】Deep copy of objects
2024-10-20 17:37:18
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()
{
}
}
}
最新文章
- [deviceone开发]-do_Webview加载JQueryMobile的示例
- git的诞生
- C++拷贝构造函数(深拷贝,浅拷贝)
- HQL 参数绑定、唯一结果、分页、投影总结(上)
- How to Optimize Battery Health?
- Google地图接口API之申请免费API Key(一)
- SQL SERVER 之 填充因子
- python os.stat() 和 stat模块详解
- redis resque消息队列
- Bzoj 1982: [Spoj 2021]Moving Pebbles 博弈论
- Jasper_sheetName_defined by parameter or hard coding or filed name
- PHP中foreach()用法汇总
- 关于activitygroup过时,用frament替换操作
- request 获取body内容
- java测试
- linux下的ssh和rynsc
- Linux在线安装git
- POJ1580 水题,积累!
- 【洛谷】P1064 金明的预算方案(dp)
- linux网络NAT配置方式