代码如下:具体看注释
[Serializable] public class A { public virtual string Name { get; set; } public int Age { get; set; } } class Program { static void Main(string[] args) { ShallowCopyTest();
DeepCopyTest();
}
// 利用序列化和反序列化的方式 public static T DeepClone<T>(T obj) { using (var ms = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); ms.Position = 0; return (T)formatter.Deserialize(ms); } } // 深复制 public static void DeepCopyTest() { List<A> a = new List<A>(); a.Add(new A { Age = 1, Name = "1" }); a.Add(new A { Age = 2, Name = "2" }); List<A> a1 = new List<A>(); a.ForEach((item) => { a1.Add(DeepClone<A>(item)); }); a1[0].Age = 10; //a[0]的Age不会受影响 Console.WriteLine(a[0].Age); Console.ReadKey(); } // 浅复制 public static void ShallowCopyTest() { List<A> a = new List<A>(); a.Add(new A { Age = 1, Name = "1" }); a.Add(new A { Age = 2, Name = "2" }); List<A> a1 = new List<A>(); a.ForEach((item) => { a1.Add(item); }); a.ForEach((item) => { a1.Add(item); }); // 列表项的内存地址只有一份 a1[0].Age = 3; // a[0]的Age也会变成3 Console.WriteLine(a[0].Age); Console.ReadKey(); } }