复杂的第三方对象/类的深层副本
这个问题在这里已经有了答案:
我会为此使用AutoMapper。 考虑以下班级定义:(note private ctor)
public class Parent
{
public string Field1 { get; set; }
public Level1 Level1 { get; set; }
public static Parent GetInstance()
{
return new Parent() { Field1 = "1", Level1 = new Level1 { Field2 = "2", Level2 = new Level2() { Field3 = "3"}}};
}
private Parent() { }
}
public class Level1
{
public string Field2 { get; set; }
public Level2 Level2 { get; set; }
}
public class Level2
{
public string Field3 { get; set; }
}
然后您可以根据需要设置AutoMapper进行深层克隆:
[TestMethod]
public void DeepCloneParent()
{
Mapper.CreateMap<Parent, Parent>();
Mapper.CreateMap<Level1, Level1>();
Mapper.CreateMap<Level2, Level2>();
var parent = Parent.GetInstance();
var copy = Mapper.Map<Parent, Parent>(parent);
Assert.IsFalse(copy == parent);//diff object
Assert.IsFalse(copy.Level1 == parent.Level1);//diff object
Assert.IsFalse(copy.Level1.Level2 == parent.Level1.Level2);//diff object
Assert.AreEqual("1", copy.Field1);
Assert.AreEqual("2", copy.Level1.Field2);
Assert.AreEqual("3", copy.Level1.Level2.Field3);
}
链接地址: http://www.djcxy.com/p/40767.html