我是靠谱客的博主 拉长金鱼,这篇文章主要介绍详解c# 深克隆与浅克隆,现在分享给大家,希望可以做个参考。

前言

我们都知道memberwiseclone 会将浅克隆。

什么是浅克隆?如何深克隆呢?

正文

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class good{ private good(){ oneclass=new class{ int id=8; string name='id'; } } private static good __good; private static good __good=new good(); public good createinstance() { return __good.memberwiseclone(); } public int a=0; public string b="ab"; pulic class oneclass; }

测试:

复制代码
1
2
3
4
5
6
7
void main() { var student1=good.createinstance(); var student2=good.createinstance(); student1.oneclass.id=9; console.log('student2 oneclass.id{0}',student2.oneclass.id); }

这里我们得出了结果为9;

ok,那么这真的是个匪夷所思的问题,明明两个对象啊。

那么回归到浅克隆上。

当克隆good的时候是这样的。

让good的classone的引用给了新的克隆对象。

那么如何深克隆呢?

深克隆其实就是将对象序列化,也就是说要深克隆的话必须对象系列化;

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class SerializeHelper { public static string Serializable(object target) { using (MemoryStream steam=new MemoryStream()) { new BinaryFormatter().Serialize(steam,target); return Convert.ToBase64String(steam.ToArray()); } } public static T Derializable<T>(string target) { byte[] targetArray = Convert.FromBase64String(target); using (MemoryStream steam =new MemoryStream(targetArray)) { return (T)(new BinaryFormatter().Deserialize(steam)); } } public static T DeepClone<T>(T t) { return Derializable<T>(Serializable(t)); } }

改变一个good 类。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class good{ private good(){ oneclass=new class{ int id=8; string name='id'; } } private static good __good; private static good __good=new good(); public good createinstance() { return SerializeHelper.DeepClone(__good.memberwiseclone()); } public int a=0; public string b="ab"; pulic class oneclass; }

测试一下:

复制代码
1
2
3
4
5
6
7
void main() { var student1=good.createinstance(); var student2=good.createinstance(); student1.oneclass.id=9; console.log('student2 oneclass.id{0}',student2.oneclass.id); }

以上就是详解c# 深克隆与浅克隆的详细内容,更多关于c# 深克隆与浅克隆的资料请关注靠谱客其它相关文章!

最后

以上就是拉长金鱼最近收集整理的关于详解c# 深克隆与浅克隆的全部内容,更多相关详解c#内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(164)

评论列表共有 0 条评论

立即
投稿
返回
顶部