Generic Deep Copy in C# for user defined classes

This question already has an answer here:

  • Deep cloning objects 39 answers

  • Try using a copy constructor for each of your classes, that can clone all your fields. You might also want to introduce an interface, eg called IDeepCloneable , that forces classes to implement a method DeepClone() which calls the copy constructor. To get the cloning type-safe without casting you can use a self-referential structure.

    Take a look at the following:

    interface IDeepCloneable<out T>
    {
        T DeepClone();
    }
    
    class SomeClass<T> : IDeepCloneable<T> where T : SomeClass<T>, new()
    {        
        // copy constructor
        protected SomeClass(SomeClass<T> source)
        {
            // copy members 
            x = source.x;
            y = source.y;
            ...
       }
    
        // implement the interface, subclasses overwrite this method to
        // call 'their' copy-constructor > because the parameter T refers
        // to the class itself, this will get you type-safe cloning when
        // calling 'anInstance.DeepClone()'
        public virtual T DeepClone()
        {
            // call copy constructor
            return new T();
        }
    
        ...
    }
    
    链接地址: http://www.djcxy.com/p/40770.html

    上一篇: C#按值复制一个对象

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