C#小知识点记录,对象的深拷贝
-
在CSDN中的定义是:
1 public static string CompareExchange( 2 ref string location1, 3 string value, 4 string comparand 5 )
用locationl与comparand进行比较,如果相等,那么locationl的值就是value的值;如果不等locationl的值就不变。函数等同于一下函数(简单模拟):
1 static string CompareExchange(ref string location1, string value, string comparand) 2 { 3 if(location1==comparand) 4 { 5 location1 = value; 6 } 7 return value; 8 }
示例:
1 string s1 = "123"; 2 string s2 = "456"; 3 string s3 = "123"; 4 string s4 = Interlocked.CompareExchange(ref s1, s2, s3); //如果s1等于s3,那么就s2的值赋给s1,表达式的值是s2的值。 5 Console.WriteLine(s1); 6 Console.WriteLine(s4);
输出:
2.知识点二
下面是一个有趣而又使用的方法,利用序列化对一个对象进行深拷贝
1 public static object DeelClone(object original) //利用序列化创建对象的深拷贝 2 { 3 4 using (MemoryStream stram = new MemoryStream()) //构造临时内存流 5 { 6 7 IFormatter formatter = new BinaryFormatter(); //构造一个序列化格式化器
8 9 formatter.Context = new StreamingContext(StreamingContextStates.Clone); 10 11 12 formatter.Serialize(stram, original); //将流对象序列化到内存流中 13 14 15 stram.Position = 0; //反序列化之前,定位到内存流德尔起始位置 16 17 18 return formatter.Deserialize(stram); //将对象图反序列化成一组新的对象图, 19 //并且返回对象图(深拷贝)的根 20 } 21 }