Deep Clone

一个使用序列化和反序列化方式实现的深度拷贝

 1 using System.IO;
 2 using System.Runtime.Serialization.Formatters.Binary;
 3 
 4 namespace PDIDataInputEndpoints.Tools
 5 {
 6     public static class Extensions
 7     {
 8         public static T DeepClone<T>(this T obj)
 9         {
10             using(MemoryStream stream =new MemoryStream())
11             {
12                 BinaryFormatter formatter = new BinaryFormatter();
13                 formatter.Serialize(stream, obj);
14                 stream.Position = 0;
15 
16                 return (T)formatter.Deserialize(stream);
17             }
18         }
19     }
20 }

测试代码:

 1         [TestMethod]
 2         public void TestMethodDeepClone()
 3         {
 4             var pdiOri = SamplePiece.SamplePieceQ23501("22050100");
 5             var pdiClone = pdiOri.DeepClone();
 6 
 7             pdiClone.IdPiece = "22050101";
 8             pdiClone.SlabData.IdMaterial = "Q235BClone";
 9 
10             Assert.AreEqual(pdiOri.IdPiece, "22050100");
11             Assert.AreEqual(pdiOri.SlabData.IdMaterial, "Q235B");
12 
13             Assert.AreEqual(pdiClone.IdPiece, "22050101");
14             Assert.AreEqual(pdiClone.SlabData.IdMaterial, "Q235BClone");
15 
16         }

可以看到对新复制的对象的修改不会影响原来的对象。

posted @ 2022-05-27 18:04  脱缰的野猪  阅读(126)  评论(0编辑  收藏  举报