利用 BinaryFormatter 实现对象的深拷贝,适用于复杂对象的复制。
using System.IO; using System.Runtime.Serialization.Formatters.Binary; [Serializable] public class Person { public string Name { get; set; } public int Age { get; set; } public List<string> Hobbies { get; set; } = new List<string>(); } public static class DeepCopyHelper { public static T DeepCopy<T>(T obj) { using (var ms = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); ms.Position = 0; return (T)formatter.Deserialize(ms); } } } // 调用示例 public static void TestDeepCopy() { var p1 = new Person { Name = "张三", Age = 25 }; p1.Hobbies.Add("编程"); var p2 = DeepCopyHelper.DeepCopy(p1); p2.Hobbies.Add("阅读"); Console.WriteLine($"p1爱好: {string.Join(",", p1.Hobbies)}"); // 编程 Console.WriteLine($"p2爱好: {string.Join(",", p2.Hobbies)}"); // 编程,阅读 }
注意:被拷贝的类必须标记 [Serializable] 特性。