Deep Copy of Complex Third Party Objects/Classes

This question already has an answer here:

  • Deep cloning objects 39 answers

  • I would use AutoMapper for this. Consider the following class definition: (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; }
    }
    

    You can then setup AutoMapper to deep clone as required:

    [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/40768.html

    上一篇: C#中的通用深度复制用于用户定义的类

    下一篇: 复杂的第三方对象/类的深层副本