DeepCloner深度复制

安装:

Install-Package DeepCloner

示例代码:

using Force.DeepCloner;

var personA = new Person() { Name = "张三", Address = new Address() { City = "杭州", Street = "采荷" } };
var personB = personA.DeepClone();
personA.Name = "李四";
personA.Address.City = "上海";

Console.WriteLine(personA.Name);
Console.WriteLine(personA.Address.City);
Console.WriteLine(personB.Name);
Console.WriteLine(personB.Address.City);

public class Person
{
    public string Name { get; set; }
    public Address Address { get; set; }
}

public class Address
{
    public string City { get; set; }
    public string Street { get; set; }
}

其它示例

var clone = new { Id = 1, Name = "222" }.DeepClone();
// public class Tree { public Tree ParentTree;  }
var t = new Tree();
t.ParentTree = t;
var cloned = t.DeepClone();
Console.WriteLine(cloned.ParentTree == cloned); // True
var date = DateTime.Now;
var obj = (object)date;
obj.DeepClone().GetType(); // DateTime

浅拷贝:

var clone = new { Id = 1, Name = "222" }.ShallowClone();
public class Derived : BaseClass
{
	public Derived(BaseClass parent)
	{
		parent.DeepCloneTo(this); // now this has every field from parent
	}
}
public class Base {}
public class Derived1 : Base {}
public class Derived2 : Base {}

var b = (Base)new Derived1(); // casting derived to parent
var derived2 = new Derived2();
// will compile, but will throw an exception in runtime, Derived1 is not parent for Derived2
b.DeepCloneTo(derived2); 
posted @ 2024-10-24 11:09  wzwyc  阅读(3)  评论(0编辑  收藏  举报