代码如下:具体看注释
[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 = ;
return (T)formatter.Deserialize(ms);
}
}
// 深复制
public static void DeepCopyTest()
{
List<A> a = new List<A>();
a.Add(new A { Age = , Name = "" });
a.Add(new A { Age = , Name = "" });
List<A> a1 = new List<A>();
a.ForEach((item) =>
{
a1.Add(DeepClone<A>(item));
});
a1[].Age = ; //a[0]的Age不会受影响
Console.WriteLine(a[].Age);
Console.ReadKey();
}
// 浅复制
public static void ShallowCopyTest()
{
List<A> a = new List<A>();
a.Add(new A { Age = , Name = "" });
a.Add(new A { Age = , Name = "" });
List<A> a1 = new List<A>();
a.ForEach((item) => { a1.Add(item); });
a.ForEach((item) => { a1.Add(item); }); // 列表项的内存地址只有一份
a1[].Age = ; // a[0]的Age也会变成3
Console.WriteLine(a[].Age);
Console.ReadKey();
}
}