前言
我们都知道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# 深克隆与浅克隆的资料请关注服务器之家其它相关文章!
原文链接:https://www.cnblogs.com/aoximin/p/13195596.html