How do you do a deep copy of an object in .NET (C# specifically)?

This question already has an answer here:

  • Deep cloning objects 39 answers

  • I've seen a few different approaches to this, but I use a generic utility method as such:

    public static T DeepClone<T>(T obj)
    {
     using (var ms = new MemoryStream())
     {
       var formatter = new BinaryFormatter();
       formatter.Serialize(ms, obj);
       ms.Position = 0;
    
       return (T) formatter.Deserialize(ms);
     }
    }
    

    Notes:

  • Your class MUST be marked as [Serializable] in order for this to work.
  • Your source file must include the following code:

    using System.Runtime.Serialization.Formatters.Binary;
    using System.IO;
    

  • I wrote a deep object copy extension method, based on recursive "MemberwiseClone" . It is fast ( three times faster than BinaryFormatter), and it works with any object. You don't need a default constructor or serializable attributes.


    Building on Kilhoffer's solution...

    With C# 3.0 you can create an extension method as follows:

    public static class ExtensionMethods
    {
        // Deep clone
        public static T DeepClone<T>(this T a)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, a);
                stream.Position = 0;
                return (T) formatter.Deserialize(stream);
            }
        }
    }
    

    which extends any class that's been marked as [Serializable] with a DeepClone method

    MyClass copy = obj.DeepClone();
    
    链接地址: http://www.djcxy.com/p/6962.html

    上一篇: 你如何克隆一个BufferedImage

    下一篇: 你如何做一个.NET对象的深层副本(特别是C#)?